d3head
d3head

Reputation: 61

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]

Upvotes: 5

Views: 1163

Answers (2)

Amit Joki
Amit Joki

Reputation: 59232

I suppose you're having input as Array of Objects and want the result in Array of Arrays, then you could just use native javascript to do it

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

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239443

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

Upvotes: 5

Related Questions