我想從我擁有的代碼開始,它確實會產生所需的輸出,但是,在我看來,使用這些嵌套的 for 回圈有點難看,我正在嘗試重構我的作業。
我的問題是您是否對重構代碼有任何建議,以便我可以避免使用這些嵌套的 for 回圈?
我想遍歷一個嵌套物件并最終得到所有唯一鍵的結果,以及該唯一鍵的所有值的陣列。
{"ABC":["1","100","6"],"DEF":["10","2","5"],"GHI":["14","9"],"HGI":["4"]}
const data = {
something: [
{
innerSomething: {
list: [
{
title: "ABC",
amount: "1"
},
{
title: "DEF",
amount: "10"
},
{
title: "GHI",
amount: "14"
}
],
}
},
{
innerSomething: {
list: [
{
title: "ABC",
amount: "100"
},
{
title: "DEF",
amount: "2"
},
{
title: "GHI",
amount: "9"
}
],
}
},
{
innerSomething: {
list: [
{
title: "ABC",
amount: "6"
},
{
title: "DEF",
amount: "5"
},
{
title: "HGI",
amount: "4"
}
],
}
}
]
};
const results = {};
data.something.forEach((item) => {
item.innerSomething.list.forEach((list) => {
if (results[list.title]) {
// exists already, just push the amount
results[list.title].push(list.amount)
} else {
// Is unique so far, add it to the object
results[list.title] = [list.amount];
}
})
});
console.log(`results: ${JSON.stringify(results)}`);
// These results are the correct and desired output
// {"ABC":["1","100","6"],"DEF":["10","2","5"],"GHI":["14","9"],"HGI":["4"]}
uj5u.com熱心網友回復:
你的實作沒問題,tbh。考慮到您的輸入物件的結構是眾所周知的,我唯一可以提出不同的建議是利用簡潔的解構模式和擴展語法:
data.something.forEach(({ innerSomething: { list } }) =>
list.forEach(({ title, amount }) =>
results[title] = [...results[title] || [], amount]))
uj5u.com熱心網友回復:
對于它的價值,這就是我的寫作方式。
const data = {
something: [
{
innerSomething: {
list: [
{
title: "ABC",
amount: "1"
},
{
title: "DEF",
amount: "10"
},
{
title: "GHI",
amount: "14"
}
],
}
},
{
innerSomething: {
list: [
{
title: "ABC",
amount: "100"
},
{
title: "DEF",
amount: "2"
},
{
title: "GHI",
amount: "9"
}
],
}
},
{
innerSomething: {
list: [
{
title: "ABC",
amount: "6"
},
{
title: "DEF",
amount: "5"
},
{
title: "GHI",
amount: "4"
}
],
}
}
]
};
const results = {};
for (let something of data.something) {
for (let item of something.innerSomething.list) {
const { title, amount } = item;
results[title] = results[title] || [];
results[title].push(amount);
}
}
console.log(`results: ${JSON.stringify(results)}`);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/445684.html
標籤:javascript
