Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Looping through a nested object and imputed missed keys

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
}
]}”’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 };
});

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading