33

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.

Termininja
  • 6,620
  • 12
  • 48
  • 49
Alexander Rutz
  • 452
  • 1
  • 4
  • 10

8 Answers8

48

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.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
12

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.

Ethan Lynn
  • 1,009
  • 6
  • 13
6
Obj = {address: 'ok', x:5}

Object.keys(obj).some(function(prop){
  return ~prop.indexOf('add')
}) //true
Edwin Reynoso
  • 1,511
  • 9
  • 18
1

You can check this also with startsWith():

Object.keys(obj).some(i => { return i.startsWith('addr') })
Termininja
  • 6,620
  • 12
  • 48
  • 49
0

Try this:

var myObject = {
    'prop1': 'value1',
    'xxxxx': 'value2'
};

var stringToCheck = 'addr';

for(var propertyName in myObject) {
    var x = propertyName.substr(0, stringToCheck.length - 1);

    if(x == stringToCheck) {
        return true;
    }
}
Jazi
  • 6,569
  • 13
  • 60
  • 92
0

I don't think "Querying" a object properties is possible. You would have to loop through the properties individually and determine if they match. something like this...

function findProp(e, prop)
{
    for(var o in e.data){
        if(o.substr(0, prop.length)==prop) //<- you could try the regex or match operation here
            return true;
    }
    return false;
}

alert(findProp({data:{addr:{street:"a", sub:"b"}}}, 'addr'));

You can then process the property if it findProp returns true...

Spock
  • 4,700
  • 2
  • 16
  • 21
0

You can write a function

function check(model) {
   var keys = [];
   for (key in model) { 
       if(key.indexOf("addr") > -1) 
           keys.push(key); 
   }
   return keys;
}
Mahib
  • 3,977
  • 5
  • 53
  • 62
-1

Why not just

var foo = {'bar':'funtimes'};
if (foo.bar.includes('fun')) {
  console.log('match');
}
Bwyss
  • 1,736
  • 3
  • 25
  • 48