Check if a Javascript Object has a property name that starts with a specific string

Alexander Rutz picture Alexander Rutz · Dec 16, 2014 · Viewed 29.4k times · Source

Lets say I have javascript objects like this one:

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.

Answer

Amit Joki picture Amit Joki · Dec 16, 2014

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.