以下有效,但我试图找到一种省略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)

答案 0 :(得分:2)
arrayOfObjects[1] = {
testParent: {
testKey: 'testValue'
}
};
事实上,您可以使用以下内容来避免数组索引器:
arrayOfObjects = [
{},
{
testParent: {
testKey: 'testValue'
}
},
{}
];
答案 1 :(得分:0)
您可以使用reduce
创建自定义方法,该方法使用字符串和值并设置嵌套属性。
let arr = [{}, {}, {}]
function set(obj, key, value) {
key.split(".").reduce((r, e, i, a) => {
return r[e] || (r[e] = a[i + 1] ? {} : value)
}, obj);
}
set(arr, "0.testParent.testKey", "testValue")
set(arr, "2.a.b.f", "value")
set(arr, "2.a.b.c", "value")
console.log(arr)
答案 2 :(得分:0)
也许小帮手可以帮助您省略括号:
const $ = (obj, key, ...keys) => key != undefined ? $(obj[key] || (obj[key] = {}), ...keys) : obj;
可用作:
const arr = [];
$(arr, 1, "testParent").testKey = "testValue";