[英]Looping through a nested object and imputed missed keys
我是 javascript 的新手,并尝试遍历嵌套的 object 以在第二级插入一个缺失的键,我想在其中添加任何低于 5 的缺失键并为其分配零值。 因此,如果我们有键 5 和 3,我想添加值为零的 4、2 和 1 键。
'''0:{"key": "2010", "values": [ { "key": "4", "value": 10 }, { "key": "3", "value": 2 } ]}
1:{“键”:“2011”,“值”:[{“键”:“5”,“值”:25},{“键”:“3”,“值”:4}]}' ''
您需要对现有数据进行 map 并检查密钥是否已经存在,希望这可以帮助您了解正在发生的事情。
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 };
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.