我有一个像这样的分组数组
this.state.tableData=
[0:{key: "EMAIL",val: ["john@example.com", "harry@example.com", "howard@example.com"]}
1:{key: "LASTNAME",val: ["Smith", "Pierce", "Paige"]}
2:{key: "FIRSTNAME",val: ["John", "Harry", "Howard"]}
3:{key: "SMS",val: ["33123456789", "33111222222", "33777888898"]}
]
我想将其转换为
之类的普通数组0: {EMAIL: "john@example.com", LASTNAME: "Smith", FIRSTNAME: "John", SMS: "33123456789"}
1: {EMAIL: "harry@example.com", LASTNAME: "Pierce", FIRSTNAME: "Harry", SMS: "33111222222"}
2: {EMAIL: "howard@example.com", LASTNAME: "Paige", FIRSTNAME: "Howard", SMS: "33777888898"}
我尝试了以下代码
this.state.csvHeaders=["EMAIL','FIRSTNAME','LASTNAME']
var contacts=[];
this.state.tableData.map(k => {
k.val.map(r => {
Object.keys(this.state.csvHeaders).forEach(key => {
if(k.val["Col"]==="EMAIL")
{
contacts[key]['EMAIL']=r;
}
})
})
})
但是它不起作用..任何建议我还可以修改。我如何存储,将它们推入数组?
答案 0 :(得分:3)
遵循这些原则应该可以起作用:
const tableData= [
{key: "EMAIL",val: ["john@example.com", "harry@example.com", "howard@example.com"]},
{key: "LASTNAME",val: ["Smith", "Pierce", "Paige"]},
{key: "FIRSTNAME",val: ["John", "Harry", "Howard"]},
{key: "SMS",val: ["33123456789", "33111222222", "33777888898"]},
];
const csvHeaders = ['EMAIL','FIRSTNAME','LASTNAME', 'SMS'];
const contacts = [];
csvHeaders.forEach( (header, idx) => {
tableData[0].val.forEach( (info, contactPos) => {
contacts[contactPos] = contacts[contactPos] || {};
contacts[contactPos][header] = tableData.find(row => row.key === header).val[contactPos];
})
})
console.log(contacts);
答案 1 :(得分:3)
您可以使用reduce和forEach做到这一点:
var tableData = [
{ key: 'EMAIL',val: ['john@example.com','harry@example.com','howard@example.com'],},
{ key: 'LASTNAME', val: ['Smith', 'Pierce', 'Paige'] },
{ key: 'FIRSTNAME', val: ['John', 'Harry', 'Howard'] },
{ key: 'SMS',val: ['33123456789', '33111222222', '33777888898'],},
];
console.log(
tableData.reduce((result, { key, val }) => {
val.forEach((val, index) => {
result[index] = result[index] || {};
result[index][key] = val;
});
return result;
}, [])
);