Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform a javascript array of object to an array of array

I am looking an elegant way in ES6 to transform this array:

var src = [{x:1,y:'a'},{x:2,y:'b'}];

To this array:

var desc = [[1,2],["a","b"]];

Which contains an array of all the properties and one array for all the values.

For this, i have written this code:

var src = [{x:1,y:'a'},{x:2,y:'b'}];

var prop1 = [];
var prop2 = [];

src.forEach(item => {
    prop1.push(item.x)
    prop2.push(item.y);
});

var desc = [prop1, prop2];

It works fine but it is quite long, so I am looking for an eventual improvement and a short code.

like image 1000
Laiso Avatar asked Jan 02 '23 13:01

Laiso


2 Answers

You name the props order (because the order of keys in object is not guaranteed) and then map over src array by extracting correspondend prop value.

var src = [{x:1,y:'a'},{x:2,y:'b'}]

var props = ['x', 'y'];

var result = props.map(prop => src.map(x => x[prop]))

console.log(result)
like image 128
Yury Tarabanko Avatar answered Jan 05 '23 17:01

Yury Tarabanko


You can use .reduce():

let src = [{x: 1, y: 'a'}, {x:2, y: 'b'}];

let result = src.reduce((a, c) => (a[0].push(c.x), a[1].push(c.y), a), [[], []]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Docs:

  • Array.prototype.reduce()
  • Array.prototype.push()
  • Comma Operator
like image 28
Mohammad Usman Avatar answered Jan 05 '23 19:01

Mohammad Usman