1

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.

2 Answers 2

4

I believe you want _.pick

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

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

3 Comments

Not sure pick is right? It takes away the properties, not the whole record?
No _.pick returns a new object containing a filtered set of key-value pairs. See the _.pick documentation I linked for an example. If you only want the values, you would also need to call _.values: underscorejs.org/#values
you are right, that's not how I read the documentation. Thanks!
0

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...

1 Comment

Thanks, my answer is similar.

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.