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

Nested Object Loop in JS

I’m trying to add a series of values to a nested object, having some trouble with the loop in the following code. Any help would be really appreciated.

let settings = {};

function write(id, values) {
    if(!settings[id]) settings[id] = {};
    for(var x = 0; x < Object.keys(values).length; x ++) {
        settings[id][values[x]] = values[values[x]];
    }
}

//example
write('example', {'prop1': 5, 'prop2': 10});

>Solution :

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

values is an object. Accessing values[x] will return undefined.

You have to access it with the correct keys in that object as below.

let settings = {};

function write(id, values) {
  if (!settings[id]) settings[id] = {};
  const keys = Object.keys(values);
  for (var x = 0; x < keys.length; x++) {
    settings[id][keys[x]] = values[keys[x]];
  }
  console.log(settings)
}

//example
write('example', { 'prop1': 5, 'prop2': 10 });
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