Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 325
Alexander Rutz Avatar asked Dec 16 '14 14:12

Alexander Rutz


People also ask

How do you check if an object has a specific property in JavaScript?

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.

How do you check if an object contains a string in JavaScript?

The includes() method returns true if a string contains a specified string. Otherwise it returns false .

How do you check if an object is a specific type JavaScript?

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.


2 Answers

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.

like image 129
Amit Joki Avatar answered Oct 06 '22 00:10

Amit Joki


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.

like image 23
Ethan Lynn Avatar answered Oct 06 '22 00:10

Ethan Lynn