[英]Array of objects to objects with properties as keys
我需要一些幫助來從一個對象數組中獲取對象,其中的鍵來自初始數組中對象的嵌套屬性。 這是最初的數組:
[
{
"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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.