Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 249
d3head Avatar asked Dec 17 '14 07:12

d3head


1 Answers

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 ] ]
like image 153
thefourtheye Avatar answered Oct 21 '22 21:10

thefourtheye