Convert array of javascript object to array array

In ES6, I was looking for an elegant way to convert 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 properties and one array for all values.

For this, I wrote 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 great, but it's quite long, so I'm looking for a possible improvement and short code.

+4
source share
3 answers

You name the requisite order (because the order of the keys in the object is not guaranteed), and then display the array src, retrieving the correspondence correction 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)
Run codeHide result
+5
source

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; }
Run codeHide result

Docs:

+3
source

, .

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

src.forEach(o => Object.keys(o).forEach((k, i) => (desc[i] = desc[i] || []).push(o[k])));

console.log(desc);
Hide result
+1

Source: https://habr.com/ru/post/1695983/


All Articles