5

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

2 Answers 2

5

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 ] ]
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.