6

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"};
3
  • 3
    Object.keys(obj).toString().indexOf('Address') !== -1 Commented Jan 8, 2016 at 5:55
  • What is your issue? Do you need to know how to get the keys of an object? Do you need to know how to loop across them? Do you need to know how to find if one string is contained in another? Commented Jan 8, 2016 at 6:01
  • Not sure if the answer I provided is what he wants, but it's what he is currently asking for. @Tushar's solution is better for the exact spec, but if OP ever needs to check each key with a regex, my solution might cover that more easily. Commented Jan 8, 2016 at 6:08

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Why the ^ at the beginning, since the spec was "containing"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.