简体   繁体   中英

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...

You have to initialize names[field] with an empty object first :

 let names = { field1: 'ton', field2: {} } field='field2' relative='brotherage' names[field][relative] = 30 field='field2' relative='cousinage' names[field][relative] = 20 console.log(names) 

使用空对象初始化field2字段:

let names = { field1: 'ton', field2: {} }

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

// has no effect in my code, why ?

Because names[ "field2" ] is null and you code is error'ng out as

Uncaught TypeError: Cannot set property 'brotherage' of null

You need to make it first make it an object

names[field] = names[field] || {}; 
names[field][relative] =  30; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM