Convert object to array with underscore

I am trying to hide a javascript object in an array using Underscore, but I am having some trouble understanding Underscore. I want to hide this:

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

      

In it:

[value1, value2],[value1, value2]

      

+3


source to share


2 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 want a 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 ] ]

      

+3


source


I assume you have input as Array

objects and require the result in Array

arrays, then you can just use native javascript to do this



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

      

0


source







All Articles