1

I have a table

const header = ["name", "age", "hobby"];
const content = [ ["Eva", 3, "dance"],
                  ["Kevin", 5, "ball"],
                  ...];

How can I get output as an array of objects?

[{name: "Eva", age: 3, hobby: "dance"}, 
 {name: "Kevin", age: 5, hobby: "ball"},
 ...]
Yixing Liu
  • 2,179
  • 1
  • 20
  • 36

3 Answers3

1

Lodash (or underscore.js) library provides some nice functions to transform data. It's just one line:

import _  from 'lodash';
const output = content.map((row) => _.zipObject(row, header));
Yixing Liu
  • 2,179
  • 1
  • 20
  • 36
1

You can do like this with javascript :

const header = ["name", "age", "hobby"];
const content = [["Eva", 3, "dance"],
 ["Kevin", 5, "ball"]
];
const result = [];

for (var i = 0; i < content.length; i++) {
 var obj = {};
 for (var j = 0; j < header.length; j++) {
  obj[header[j]] = content[i][j];
 }
 result.push(obj);
}
console.log(result);
Jagjeet Singh
  • 1,564
  • 1
  • 10
  • 23
0

can be done with map and reduce

const header = ["name", "age", "hobby"];
const content = [
  ["Eva", 3, "dance"],
  ["Kevin", 5, "ball"]
];

console.log(content.map((item) => {
  return header.reduce((acc, cur, i) => {
    acc[cur] = item[i];
    return acc;
  }, {});
}));
D. Seah
  • 4,472
  • 1
  • 12
  • 20