我有一个JSON对象:
{
"columnNames": [
"Incident ID",
"IncidentType"
],
"rows": [
[
"3599590",
"Telecommuting/VWA Empl- Initiate"
],
[
"3599601",
"Telecommuting/VWA Empl- Initiate"
]
]
}我想将Javascript中的这个对象转换为这个对象:
{
reportResults: [{
"Incident ID": "3599590",
"IncidentType": "Telecommuting/VWA Empl- Initiate"
},
{
"Incident ID": "3599591",
"IncidentType": "Telecommuting/VWA Empl- Initiate"
}
]
}在以下示例中,我尝试使用push函数:
VWA_Output = {
"columnNames": [
"Incident ID",
"IncidentType"
],
"rows": [
[
"3599590",
"Telecommuting/VWA Empl- Initiate"
],
[
"3599601",
"Telecommuting/VWA Empl- Initiate"
]
]
};
JSTest_JSON_Var1 = {
reportResults: []
};
for (i in VWA_Output.rows) {
for (var j in VWA_Output.rows[i]) {
var key = VWA_Output.columnNames[j];
var value = VWA_Output.rows[i][j]
JSTest_JSON_Var1.reportResults.push({
[key]: value
});
}
}
console.log(JSTest_JSON_Var1);但是,它似乎使用集合作为单独的数组元素创建这样的对象:
{
[{
"reportResults": [{
"Incident ID": "3599590"
}, {
"IncidentType": "Telecommuting/VWA Empl- Initiate"
}
},
{
"Incident ID": "3599591"
},
{
"IncidentType": "Telecommuting/VWA Empl- Initiate"
}
}]
}我希望列和行的集合是数组中的单个记录集合:
{
"reportResults": [{
"Incident ID": "3599590",
"IncidentType": "Telecommuting/VWA Empl- Initiate"
}, {
"Incident ID": "3599591",
"IncidentType": "Telecommuting/VWA Empl- Initiate"
}]
}谢谢!
发布于 2021-12-16 05:18:03
一次性定义reportResults -让它的内容是一个从rows映射的数组,在这个数组中,您使用要迭代的列名的索引来访问适当的行值。我会使用Object.fromEntries来保持简洁。
const input = {
"columnNames": [
"Incident ID",
"IncidentType"
],
"rows": [
[
"3599590",
"Telecommuting/VWA Empl- Initiate"
],
[
"3599601",
"Telecommuting/VWA Empl- Initiate"
]
]
};
const output = {
reportResults: input.rows.map(row => Object.fromEntries(
input.columnNames.map((name, i) => [name, row[i]])
))
};
console.log(output);
发布于 2021-12-16 05:19:12
假设示例数据在data中
const result = {
"reportResults" : data.rows.map(row => {
return {
[data.columnNames[0]]: row[0],
[data.columnNames[1]]: row[1]
}
})
}发布于 2021-12-16 05:24:44
这是我的解决办法:
var data = {
"columnNames": [
"Incident ID",
"IncidentType"
],
"rows": [
[
"3599590",
"Telecommuting/VWA Empl- Initiate"
],
[
"3599601",
"Telecommuting/VWA Empl- Initiate"
]
]
}
var reportResults = data.rows.map((row) =>
Object.assign({}, ...row.map((cell, i) => ({ [data.columnNames[i]]: cell})))
)
console.log({reportResults})不是最优的,而是短的)
https://stackoverflow.com/questions/70374088
复制相似问题