0

I am trying to dynamically create an n dim object finalObj looking like this for n=3

children = { 'value1' : 'some1' , 'value2' : 'some2' , 'value3' :'some3' }

    item = { 'key1' : 'value1' , 'key2':'value2' , 'key3':'value3' }

basically, the resulting object would look like this.

 finalObj  =  { parent : { 'some1' : { 'some2' : { 'some3':{} } } } } 

I am creating an n-depth Object below here.

var parent ={} 
var finalObj

function makechildren( children, depth ){  
  if (depth>0){       
    makechildren({children}, depth-1);  
  }
  else
  { finalObj=children 
  console.log('finalObj',finalObj) 

  }
  return finalObj
 }

 Promise.resolve(makechildren(parent,4))
 .then(function(resp){
  console.log("resp is",resp); 
  })

This prints:

{ "children": { "children": { "children": { "children": {} } } } }

Now, how to turn

parent.children.children.children

with

item ={'key1':'value1','key2':'value2','key3':'value3'}

into

parent.children[ item['key1']].children[ item['key2']].children[ item['key3']] 

which is essentially

parent.children['value1'].children['value2'].children['value3']....

I have tried making a copy of the original dictionary and altering the keys with a loop and assigning each parent.children[ item['key1']] to the rest of the multidimensional dictionary but didnt go really far.

parent1 = JSON.parse(JSON.stringify(parent))
for (i in Object.keys(parent))
{ 
parent1[ item['key'+i] ] = parent.children
}

However, iam stuck here on how to complete it this way. Any idea?

0

1 Answer 1

1

Loop through the values in item, using each one to get the corresponding value from children, and use this as the property for a new object. To make the nested object, use a variable to hold the object at the current depth, which you update each time through the loop.

children = { 'value1' : 'some1' , 'value2' : 'some2' , 'value3' :'some3' };

item = { 'key1' : 'value1' , 'key2':'value2' , 'key3':'value3' };

finalObj = { parent: {} };

var cur = finalObj.parent;
Object.values(item).forEach(val => {
    cur[children[val]] = {};
    cur = cur[children[val]];
});

console.log(JSON.stringify(finalObj));

Note that the order of items read from an object is not guaranteed, so there's no assurance that this will nest things in the desired order. You should use an array if you want order to be maintained.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.