I'm new to javascript and trying to loop through a nested object to insert a missing key at the second level where I would like to add any missing keys below 5 and assign them a value of zero. So if we have keys 5 and 3, I would like to add 4, 2, and 1 keys with a value of zero.
'''0:{"key": "2010", "values": [ { "key": "4", "value": 10 }, { "key": "3", "value": 2 } ]}
1:{"key": "2011", "values": [ { "key": "5", "value": 25 }, { "key": "3", "value": 4 } ]}'''
CodePudding user response:
You need to map over the existing data and check to see if the key exists already, hope this helps you understand what's happening.
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 };
});