gpt4 book ai didi

javascript - 对象数组到以属性为键的对象

转载 作者:行者123 更新时间:2023-11-29 16:01:15 25 4
gpt4 key购买 nike

我需要一些帮助来从对象数组中获取对象,这些对象的键来自初始数组中对象的嵌套属性。这是初始数组:

[  
{
"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);

最佳答案

你不需要在 reduce 之外维护临时变量,你可以简单地在 reduce 本身中处理相同的操作

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"
}
];
const mappedObj = initialArray.reduce((obj, item) => {
obj[item.id.recId] = {...(obj[item.id.recId] || {}), [item.id.colName]: {desc: item.desc, resCode: item.resCode}}
return obj;
}, {});
console.log(mappedObj);

关于javascript - 对象数组到以属性为键的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52946528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com