我有一个对象:
let names = { field1: 'ton', field2: null } // or field3 does not exist
我需要将name对象中的变量元素插入到
field='field2'
relative='brotherage'
names[field][relative] = 30; // has no effect in my code, why ?
得到这个:
{ field1: 'ton', field2: {brotherage: 30 } }
并使用此类代码向字段添加更多元素:
field='field2'
relative='cousinage'
names[field][relative] = 20; // has no effect in my code, why ?
得到这个:
{ field1: 'ton', field2: {brotherage: 30, cousingage: 30 } }
什么是最好的方法或为什么我失败了...我尝试过很多东西但是我迷路了......
答案 0 :(得分:2)
您必须首先使用空对象初始化names[field]
:
let names = { field1: 'ton', field2: {} }
field='field2'
relative='brotherage'
names[field][relative] = 30
field='field2'
relative='cousinage'
names[field][relative] = 20
console.log(names)
答案 1 :(得分:1)
使用空对象初始化field2
字段:
let names = { field1: 'ton', field2: {} }
答案 2 :(得分:1)
如果属性具有假值或不存在,则可以使用默认对象。
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);
答案 3 :(得分:1)
//对我的代码没有影响,为什么?
因为names[ "field2" ]
是null
而你的代码是错误的
未捕获的TypeError:无法设置属性' brotherage'为null
你首先需要让它成为一个对象
names[field] = names[field] || {};
names[field][relative] = 30;