1

I have an array of data [{a:12,b:20},{a:20,b:123}]

How I can convert this to [[12,20],[20,123]]

3

4 Answers 4

4

You can use Array.map() using Object.Values() as the mapping method:

let input = [{a:12,b:20}, {a:20,b:123}];
let res = input.map(Object.values);
console.log(JSON.stringify(res));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

If you need to rely on order of the keys, then refer to @MarkMeyer answer, it can be more appropriate for your purposes.

Sign up to request clarification or add additional context in comments.

3 Comments

This makes some assumptions about the key order doesn't it?
@MarkMeyer you are right, however he don't specify nothing about order and I was thinking more about a general approach (i.e when more keys can exists and the objects can have differents keys). I see too that your answer is more appropiated if he need ordering.
I will say the succinctness of it is very attractive.
4

It's a pretty one-liner with some destructuring:

let l = [{a:12,b:20},{a:20,b:123}]
let arr = l.map(({a, b}) => ([a, b]))

console.log(arr)

1 Comment

As I say on my answer, this is a more appropriate approach if you need to rely on the order of the keys and deserves my upvote.
0

const data = [{a:12,b:20},{a:20,b:123}]
let result = []
data.forEach(d => result.push([d.a,d.b]))
console.log(result)

Comments

0

Extract the keys and loop it with your input variable. i have used map function to loop and get data in array format.

var input = [{a:12,b:20},{a:20,b:123}];

var keys = Object.keys(input[0]);

var output = [];

keys.forEach(function(key){
output.push(input.map((item) => item[key]))
})
console.log(output)

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.