假设我想分配一个这样的值:
x.label1.label2.label3 = someValue;
// or equivalently:
x['label1']['label2']['label3'] = someValue;
只要定义了 x.label1.label2
就可以工作,否则会遇到引用错误。这当然是有道理的。但是有没有一种简单的方法可以在它只创建必要的嵌套对象的地方分配它?
例如,如果 x
等于 { label1: {}, otherLabel: 'otherValue' }
我想更新 x
成为{ label1: { label2: { label3: someValue } }, otherLabel: otherValue }
我想我也许可以自己编写一个函数,但是是否有语言功能或标准库函数可以做到这一点?
最佳答案
is there a language feature or standard library function that does this
没有。您必须编写自己的函数或使用提供此类功能的库。
相关:How to set object property (of object property of..) given its string name in JavaScript?
关于javascript - 在(部分) undefined object 中分配嵌套值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38816438/