5

I have fairly lot of data in this form

A B C D
-------
1 2 3 4
5 6 7 8
9 1 2 3

represented using javascript types as :

df = {A: [1,5,9], B: [2,6,1], C: [3,7,2], D:[4,8,3]}

I want to convert this into this form:

[{A:1, B:2, C:3, D:4}, {A:5, B:6, C:7, D:8}, {A:9, B:1, C:2, D:3}]

I tried implementing it as:

keyes = ["A", "B", "C", "D"]
getrow = (i) => Object.assign( ...keyes.map((k) => ({[k]: df[k][i]})))
df.A.map( (x,j) => getrow(j))

But this is slow for the size of the table I have. Is there any faster way to do this?

asked Sep 5, 2019 at 17:17
0

2 Answers 2

5

You could use reduce and forEach loops to create array of objects.

const df = {
 A: [1, 5, 9],
 B: [2, 6, 1],
 C: [3, 7, 2],
 D: [4, 8, 3]
}
const result = Object.keys(df).reduce((r, k) => {
 df[k].forEach((e, i) => {
 if (!r[i]) r[i] = {}
 r[i][k] = e;
 })
 return r;
}, [])
console.log(result)

Or maybe for better performance you can go with the for loops.

const df = {
 A: [1, 5, 9],
 B: [2, 6, 1],
 C: [3, 7, 2],
 D: [4, 8, 3]
}
const result = [];
for (let key in df) {
 for (let i = 0; i < df[key].length; i++) {
 if (!result[i]) result[i] = {}
 result[i][key] = df[key][i]
 }
}
console.log(result)

answered Sep 5, 2019 at 17:23
Sign up to request clarification or add additional context in comments.

Comments

3

You could take two for loops, and check the existence of the object at a certain index. Then assign the value to the property.

This version is faster than the use of array methods.

var data = { A: [1, 5, 9], B: [2, 6, 1], C: [3, 7, 2], D: [4, 8, 3] },
 result = [],
 key, values,
 i;
 
for ([key, values] of Object.entries(data)) {
 for (i = 0; i < values.length; i++) {
 if (!result[i]) result[i] = {};
 result[i][key] = values[i];
 }
}
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

answered Sep 5, 2019 at 17:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.