How to check if a JavaScript Object has a property name that starts with a specific string?

34,502

Solution 1

You can check it against the Object's keys using Array.some which returns a bool.

if(Object.keys(obj).some(function(k){ return ~k.indexOf("addr") })){
   // it has addr property
}

You could also use Array.filter and check it's length. But Array.some is more apt here.

Solution 2

You can use the Object.keys function to get an array of keys and then use the filter method to select only keys beginning with "addr".

var propertyNames = Object.keys({
    "addr:housenumber": "7",
    "addr:street": "Frauenplan",
    "owner": "Knaut, Kaufmann"
}).filter(function (propertyName) {
    return propertyName.indexOf("addr") === 0;
});
// ==> ["addr:housenumber", "addr:street"];

This gives you existence (propertyNames.length > 0) and the specific names of the keys, but if you just need to test for existence you can just replace filter with some.

Solution 3

Obj = {address: 'ok', x:5}

Object.keys(obj).some(function(prop){
  return ~prop.indexOf('add')
}) //true

Solution 4

You can check this also with startsWith():

Object.keys(obj).some(i => { return i.startsWith('addr') })
Share:
34,502
Alexander Rutz
Author by

Alexander Rutz

Updated on July 18, 2022

Comments

  • Alexander Rutz
    Alexander Rutz almost 2 years

    Lets say I have javascript objects like this one:

    var obj = {
        'addr:housenumber': '7',
        'addr:street': 'Frauenplan',
        'owner': 'Knaut, Kaufmann'
    }
    

    How can I check if the object has a property name that starts with addr? I’d imagine something along the lines of the following should be possible:

    if (e.data[addr*].length) {
    

    I tried RegExp and .match() to no avail.

  • Alexander Rutz
    Alexander Rutz over 9 years
    Cheers to all! This one seems to be the shortest and most elegant way to do it.
  • Alexander Rutz
    Alexander Rutz over 9 years
    @Edwin brilliant, even more elegant!
  • Edwin Reynoso
    Edwin Reynoso over 9 years
    lol alright soon it'll be easier with fat arrow functions in ES6
  • Amit Joki
    Amit Joki over 9 years
    @Edwin yeah.. Object.keys(obj.some((k) => ~k.indexOf("addr"));. Waiting for it to come :)
  • Edwin Reynoso
    Edwin Reynoso over 9 years
    Me too Me too can't wait
  • zookastos
    zookastos over 7 years
    What is the role of ~ here?
  • Skywalker13
    Skywalker13 about 6 years
    Note that with a very large object, it's not very efficient because Object.keys() is generated before the call with some(); it's more efficient to check property by property with a for in.
  • Erwin Lengkeek
    Erwin Lengkeek over 5 years
    Because it is regarding the key, not the value.
  • Sweet Chilly Philly
    Sweet Chilly Philly almost 4 years
    What is the Tilders functionality here?