简体   繁体   English

将表格转换成JavaScript中的对象数组

[英]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. Lodash (或underscore.js )库提供了一些不错的函数来转换数据。 It's just one line: 这只是一行:

import _  from 'lodash';
const output = content.map((row) => _.zipObject(row, header));

You can do like this with javascript : 您可以使用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;
  }, {});
}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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