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

Subash
  • 3,128
  • 6
  • 30
  • 44
  • 2
    Possible duplicate of [How to convert an Object to an Array of key-value pairs in JavaScript](https://stackoverflow.com/questions/38824349/how-to-convert-an-object-to-an-array-of-key-value-pairs-in-javascript). – N'Bayramberdiyev Apr 05 '19 at 03:12
  • 2
    Possible duplicate of [How to convert an Object {} to an Array \[\] of key-value pairs in JavaScript](https://stackoverflow.com/questions/38824349/how-to-convert-an-object-to-an-array-of-key-value-pairs-in-javascript) – Andreas Apr 05 '19 at 03:19
  • That's not a dupe, guys - it's about converting `{a: 12}` into `["a", 12]` not into `[12]` – VLAZ Apr 05 '19 at 03:52

4 Answers4

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.

Shidersz
  • 16,846
  • 2
  • 23
  • 48
  • This makes some assumptions about the key order doesn't it? – Mark Apr 05 '19 at 03:29
  • @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. – Shidersz Apr 05 '19 at 03:35
  • I will say the succinctness of it is very attractive. – Mark Apr 05 '19 at 03:36
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)
Mark
  • 90,562
  • 7
  • 108
  • 148
  • 1
    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. – Shidersz Apr 05 '19 at 03:40
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)
holydragon
  • 6,158
  • 6
  • 39
  • 62
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)
Alaksandar Jesus Gene
  • 6,523
  • 12
  • 52
  • 83