简体   繁体   中英

Underscore: How to return all values by array with keys

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)
});

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]
});

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM