Search code examples
javascriptecmascript-2016

assign an key value inside a sub key in object


I have an object:

let names = { field1: 'ton', field2: null }  // or field3 does not exist

and I need to insert accord to an variable elements inside names object, to

field='field2'
relative='brotherage'
names[field][relative] =  30;  // has no effect in my code, why ?

to get this:

 { field1: 'ton', field2: {brotherage: 30 } }

and add more elements to fields with this type of code:

field='field2'
relative='cousinage'
names[field][relative] =  20;  // has no effect in my code, why ?

to get this:

 { field1: 'ton', field2: {brotherage: 30, cousingage: 30 } }

what is the best methos or why i'm failing... i've tried a lot of things but i get lost...


Solution

  • You could use a default object if the property has a falsy value or does not exists.

    var names = { field1: 'ton', field2: null },
        field = 'field2',
        field1 = 'field3', 
        relative = 'brotherage';
        relative1 = 'inlaw';
        
    names[field] = names[field] || {};
    names[field][relative] =  30;
    
    names[field1] = names[field1] || {};
    names[field1][relative1] =  40;
    
    console.log(names);