【发布时间】:2019-03-27 13:01:41
【问题描述】:
我需要一些帮助才能从对象数组中获取对象,其中的键来自初始数组中对象的嵌套属性。这是初始数组:
[
{
"id":{
"colName":"columnA",
"recId":"123"
},
"desc":"this is a description for A",
"resCode":"-1"
},
{
"id":{
"colName":"columnB",
"recId":"123"
},
"desc":"this is a description for B",
"resCode":"-1"
},
{
"id":{
"colName":"columnC",
"recId":"234"
},
"desc":"description for column c ",
"resCode":"-1"
}
];
我想要的输出是这样的:
{
123: {
columnA: {
desc: "this is a description for A",
rescode: "-1"
}
columnB: {
desc: "this is a description for B",
rescode: "-1"
}
},
234: {
columnC: {
desc: "description for column c ",
resCode: "-1",
}
}
}
我尝试使用 reduce 来执行此操作,但我遇到了问题。我不知道如何(以及何时)“清除”临时变量,所以我只能拥有属于一个 recId 的列名。
const initialArray = [
{
"id": {
"colName": "columnA",
"recId": "123"
},
"desc": "this is a description for A",
"resCode": "-1"
},
{
"id": {
"colName": "columnB",
"recId": "123"
},
"desc": "this is a description for B",
"resCode": "-1"
},
{
"id": {
"colName": "columnC",
"recId": "234"
},
"desc": "description for column c ",
"resCode": "-1"
}
];
let temp = {};
const mappedObj = initialArray.reduce((obj, item) => {
temp[item.id.colName] = Object.assign({}, {desc: item.desc}, {resCode: item.resCode} );
obj[item.id['recId']] = Object.assign({}, temp);
return obj;
}, {});
console.log(mappedObj);
【问题讨论】:
标签: javascript arrays object reduce