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

时间:2018-07-24 03:34:45

标签: javascript lodash

我有一张桌子

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

如何获取作为对象数组的输出?

[{name: "Eva", age: 3, hobby: "dance"}, 
 {name: "Kevin", age: 5, hobby: "ball"},
 ...]

3 个答案:

答案 0 :(得分:1)

const clinics={"a0CW0000001K2F8MAK":{"id":"a0CW0000001K2F8MAK","invitations":{"56205":{"id":"56205","status":"Confirmed",},}},"a0CW00000026gjsMAA":{"id":"a0CW00000026gjsMAA","invitations":{}},"a0CW00000026gjTMAQ":{"id":"a0CW00000026gjTMAQ","invitations":{"56445":{"id":"56445","status":"Cancelled",},}},"a0CW00000026gipMAA":{"id":"a0CW00000026gipMAA","invitations":{"56447":{"id":"56447","status":"Confirmed",},"56448":{"id":"56448","status":"Cancelled",},"56456":{"id":"56456","status":"Declined",}}},"a0CW00000026gjOMAQ":{"id":"a0CW00000026gjOMAQ","invitations":{}},"a0CW00000026gjnMAA":{"id":"a0CW00000026gjnMAA","invitations":{"56304":{"id":"56304","status":"Pending",},}},} console.log( Object.entries(clinics).reduce((a, [key, val]) => { const { invitations } = val; if (Object.values(invitations).some(({ status }) => status === 'Cancelled')) { a[key] = val; } return a; }, {}) );(或Lodash)库提供了一些不错的函数来转换数据。只有一行:

underscore.js

答案 1 :(得分:1)

您可以使用 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);

答案 2 :(得分:0)

可以通过map和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;
  }, {});
}));