0

Assume I have an object as;

test = Object
    3232@alex= Object
    5656@alex= Object
    8383@felix= Object
    98232@tom= Object

I want to get the objects in test where the key value contains alex, I mean the first two objects.

3232@alex= Object
5656@alex= Object

Normally I reach them as test["3232@alex"] or test."3232@alex". Now can I write a regex expression to get the objects where key contains "alex" for example.I know I can loop through the object as;

var arr = [];
for(var key in test){
    if(key.contains("alex")){
       arr.push(test[key]);
    }
}

Is it the only way to do it? I'm actually looking for a solution which avoids loop.

mmu36478
  • 1,295
  • 4
  • 19
  • 40
  • think loop is most fastest way to do it. Also, `test."3232@alex"` will not work. – degr May 31 '17 at 10:58
  • also, you can do this one Object.keys(test).forEach(function(v){if(v.contains)...}), but it will not work in IE9. – degr May 31 '17 at 10:59
  • There are other ways of doing this, have a look at [this](https://stackoverflow.com/questions/5072136/javascript-filter-for-objects), but fundamentally you are going to have a loop over the object keys somewhere, it can't be avoided. – Karl Reid May 31 '17 at 11:00
  • @degr Nor will it work in Netscape Navigator. –  May 31 '17 at 11:08

1 Answers1

2

I'm actually looking for a solution which avoids loop.

You have a bunch of things (object keys) that you want to look through to find matching ones. "Looking through" is by definition a loop. You can't avoid a loop. The only question is whether you will write the loop yourself (for (...)), or use some library utility or function that loops for you behind the scenes. Which to use is to some extent a matter of preference. It would not be surprising if the loop you wrote yourself ran faster, in case you care.

One example is filter:

Object.keys(test)
  .filter(key => /alex/.test(key)
  .forEach(key => console.log(key, test[key]));