Reputation: 283
How to find whether a JavaScript object has key with specific regex pattern ? For example, in the below object, how to find whether it contains a key containing the word "Address"?
var obj = {Address_Line1 : "XXX", Address_Line2 :"YYY", Name : "ZZZ"};
Upvotes: 6
Views: 7421
Reputation: 5379
Sure - you can do this with Array.prototype.some
and Object.keys
, like so:
var obj = {Address_Line1 : "XXX", Address_Line2 :"YYY", Name : "ZZZ"};
var hasKeyRegex = Object.keys(obj).some(function(key) {
return /Address/.test(key);
});
console.log(hasKeyRegex);
hasKeyRegex
will be true
if the object has a key containing Address
, and false
if not.
Upvotes: 9