emd
emd

Reputation: 414

Filter object by key array

I have an object that looks like this:

tagCount = {key1: val1, key2: val2...keyn:valn}

And an array that looks like this:

keys = ['key1', 'key3', 'key5'];

I want to get an object (or an array I guess) from tagCount with only the fields that match keys:

foo - {key1: val1, key3: val3, key5: val5}

I use Underscore so I feel like this is possible but for the life of me I cannot figure out the magic to make it happen.

Upvotes: 1

Views: 134

Answers (2)

Mike Robinet
Mike Robinet

Reputation: 843

I believe you want _.pick

Should be something like this: _.pick(tagCount, keys)

Upvotes: 4

brybott
brybott

Reputation: 157

not using underscore...

var result = [];
for (var i in keys; i<keys.length; i++){
  if (tagCount.hasOwnProperty(keys[i])){
    result.push(tagCount[keys[i]]);
  }
}
console.log(result)

I think it should work...

Upvotes: 0

Related Questions