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
Suresh
9671 gold badge12 silver badges29 bronze badges
2 Answers 2
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
Nenad Vracar
122k16 gold badges160 silver badges184 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Comments
lang-js