How to check if a JavaScript Object has a property name that starts with a specific string?
34,502
Solution 1
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.
Solution 2
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
.
Solution 3
Obj = {address: 'ok', x:5}
Object.keys(obj).some(function(prop){
return ~prop.indexOf('add')
}) //true
Solution 4
You can check this also with startsWith():
Object.keys(obj).some(i => { return i.startsWith('addr') })
Author by
Alexander Rutz
Updated on July 18, 2022Comments
-
Alexander Rutz almost 2 years
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. -
Alexander Rutz over 9 yearsCheers to all! This one seems to be the shortest and most elegant way to do it.
-
Alexander Rutz over 9 years@Edwin brilliant, even more elegant!
-
Edwin Reynoso over 9 yearslol alright soon it'll be easier with fat arrow functions in ES6
-
Amit Joki over 9 years@Edwin yeah..
Object.keys(obj.some((k) => ~k.indexOf("addr"));
. Waiting for it to come :) -
Edwin Reynoso over 9 yearsMe too Me too can't wait
-
zookastos over 7 yearsWhat is the role of ~ here?
-
Skywalker13 about 6 yearsNote that with a very large object, it's not very efficient because
Object.keys()
is generated before the call withsome()
; it's more efficient to check property by property with afor in
. -
Erwin Lengkeek over 5 yearsBecause it is regarding the key, not the value.
-
Sweet Chilly Philly almost 4 yearsWhat is the Tilders functionality here?