0

I have big object with a lot of key : value, and I have array with some keys from this object.

How to return values of this keys(array) by underscore?

I try some like this, but it's bull**

_.find(objectwithkeysandvalues ,  function(value){
    return _.intersection(value,arraywithekeys)
});

3 Answers 3

3

You don't need Underscore for this task. Instead, you can use the map function to create a new array that contains the values specified by the keys in the old array:

var myValues = keys.map(function (key) {
    return myObject[key]
});
Sign up to request clarification or add additional context in comments.

Comments

0

You only need to map each value from your keys array to yourBigObject[value].

In Underscore this would look like this :

var keys = [ ... ]; // Keys from your big object
var obj = { ... }; // Your big object
var values = _.map(keys, function(value, index) {
    return obj[value];
});

See this fiddle for experimenting.

Comments

0

Here's a solution using upcoming EcmaScript 7 Array Comprehensions available today via Babel.js.

Try it: Array Comprehensions Example.

ES7:

var obj = {
  "key1": 1,
  "key2": 2,
  "key3": 3
}

var arr = ["key1"];

var values = [for(key of arr) obj[key]];

console.log(values);

Comments

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.