我是 javascript 新手,并試圖回圈遍歷嵌套物件以在第二級插入缺少的鍵,我想添加低于 5 的任何缺少的鍵并將它們分配為零值。因此,如果我們有鍵 5 和 3,我想添加值為零的 4、2 和 1 鍵。
'''0:{"key": "2010", "values": [ { "key": "4", "value": 10 }, { "key": "3", "value": 2 } ]}
1:{“key”:“2011”,“values”:[{“key”:“5”,“value”:25},{“key”:“3”,“value”:4}]}' ''
uj5u.com熱心網友回復:
您需要映射現有資料并檢查密鑰是否已經存在,希望這可以幫助您了解正在發生的事情。
let data = [
{
key: "2010",
values: [
{ key: "4", value: 10 },
{ key: "3", value: 2 },
],
},
{
key: "2011",
values: [
{ key: "5", value: 25 },
{ key: "3", value: 4 },
],
},
];
data = data.map((currentItem) => {
// Create a new temp values array
const newValues = [];
// Ensure all keys are present (between 1 and 5)
for (let i = 1; i <= 5; i ) {
// Check to see if the key already exists
const existingValue = currentItem.values.find(({ key }) => key === String(i));
// Insert the existing value or initialise the key to 0
newValues.push({ key: String(i), value: existingValue ? existingValue.value : 0 });
}
// Return the new object, replacing the values array with the new one
return { ...currentItem, values: newValues };
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/512551.html
