Check if a Javascript Object has a property name that starts with a specific string
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.
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
.
Obj = {address: 'ok', x:5}
Object.keys(obj).some(function(prop){
return ~prop.indexOf('add')
}) //true