简体   繁体   中英

Convert object to an array with underscore

I'm trying to covert javascript object to an array using Underscore, but I have some problems with understanding Underscore. I want to covert this:

{ key1: value1, key2: value2},{key1: value1, key2: value2}

Into this:

[value1, value2],[value1, value2]

You can use _.map and _.values like this

var data = [{ key1: 1, key2: 2 }, { key1: 3, key2: 4 }];
console.log(_.map(data, _.values));
# [ [ 1, 2 ], [ 3, 4 ] ]

If you fancy generic JavaScript version, you can do

console.log(data.map(function(currentObject) {
    return Object.keys(currentObject).map(function(currentKey) {
        return currentObject[currentKey];
    })
}));
# [ [ 1, 2 ], [ 3, 4 ] ]

我想您将输入作为对象Array ,并希望将结果作为Array数组,那么您可以使用本机javascript来做到这一点

var output = input.map(function(obj){ return [obj.key1, obj.key2] });

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