2

Javascript in a browser environment. I wish to get all keys in a JSON object that match a specific pattern. Say, all of them that begin with mystring. Is there a simpler/efficient way of doing that without having to iterate through all the keys ?

{
   somekey1: "someval1",
   somekey2: "someval2",
   mystringkey1: "someval",
   mystringkey2: "someval"

}

There had been similar questions, but a) doesn't fully answer this question and b) JQuery is not an option at the moment.

Community
  • 1
  • 1
Alavalathi
  • 713
  • 2
  • 9
  • 21

2 Answers2

5

As mentioned in the comments, iterate through your object and add to a result when you find a matching key.

var data = {
   somekey1: "someval1",
   somekey2: "someval2",
   mystringkey1: "someval",
   mystringkey2: "someval"
}

var filtered = {}

for (key in data) {
    if (key.match(/^mystring/)) filtered[key] = data[key];
}

console.log(filtered)
Kristján
  • 18,165
  • 5
  • 50
  • 62
3

Use Object.keys and filter

var myObj = {
  somekey1: "someval1",
  somekey2: "someval2",
  mystringkey1: "someval",
  mystringkey2: "someval"

};

var pattern = /^mystring/;
var matchingKeys = Object.keys(myObj).filter(function(key) {
  return pattern.test(key);
});

console.log(matchingKeys);
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53