gpt4 book ai didi

javascript - 如何使用括号表示法在对象文字上创建嵌套属性?

转载 作者:行者123 更新时间:2023-12-01 01:57:33 29 4
gpt4 key购买 nike

以下内容有效,但我正在尝试找到一种方法来省略 arrayOfObjects[1]['testParent'] = {}位,假设您想要向嵌套了 10 级的空对象添加一个值,则必须使用空 {} 初始化每个级别。首先,我试图找到解决方法。

let arrayOfObjects = [
{},
{},
{},
]

arrayOfObjects[1]['testParent'] = {}
arrayOfObjects[1]['testParent']['testKey'] = 'testValue'

// is there a way to do the above in one line, without having to initialize testParent with an empty object on line 7?

console.log(arrayOfObjects)

最佳答案

 arrayOfObjects[1] = {
testParent: {
testKey: 'testValue'
}
};

事实上,您也可以避免使用数组索引器,例如:

 arrayOfObjects = [ 
{},
{
testParent: {
testKey: 'testValue'
}
},
{}
];

关于javascript - 如何使用括号表示法在对象文字上创建嵌套属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50891242/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com