简体   繁体   中英

turn a table into an array of objects in JavaScript

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"},
 ...]

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

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

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;
  }, {});
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM