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.
We can check if a property exists in the object by checking if property !== undefined . In this example, it would return true because the name property does exist in the developer object.
The includes() method returns true if a string contains a specified string. Otherwise it returns false .
The JavaScript instanceof operator is used to check the type of an object at the run time. It returns a boolean value(true or false). If the returned value is true, then it indicates that the object is an instance of a particular class and if the returned value is false then it is not.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With