4

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.

2
  • Possible duplicate of From an array of objects, extract value of a property as array Commented Apr 9, 2018 at 12:29
  • Actually I would keep it as you have it. It is very readable and you dont have to think about "what would be the output". Having everything in one line does not necessarily mean that it is better or "more clever"... Commented Apr 9, 2018 at 12:30

3 Answers 3

5

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)

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

3 Comments

Nice one. However could be more cool if props = Object.keys(src[0]) instead of hard coded values.
@MohammadUsman Not really. The order of keys is not guaranteed.
Yes, you are right. I forgot about order in this case.
3

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:

Comments

1

You could iterate the array and then by the keys of the object and switch the outer and inner indices the target element.

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

2 Comments

The only possible issue is that property order is not guaranteed in an object
right, i assume, the keys have the same order, as in the given code.

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.