Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create array of objects using arrays of values

Tags:

javascript

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?

like image 538
Suresh Avatar asked Sep 05 '19 17:09

Suresh


Video Answer


2 Answers

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)
like image 157
Nenad Vracar Avatar answered Sep 20 '22 02:09

Nenad Vracar


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; }
like image 42
Nina Scholz Avatar answered Sep 17 '22 02:09

Nina Scholz