![](/img/trans.png)
[英]Using only property accessors (dot notation or bracket notation), how do I set undefined nested properties directly?
[英]How do I create nested properties on object literals using bracket notation?
下面的作品,但我試圖找到一種方法來省略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'
}
},
{}
];
您可以為此創建自定義方法,方法是使用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.abf", "value") set(arr, "2.abc", "value") console.log(arr)
也許一個小幫手可以幫助您省略括號:
const $ = (obj, key, ...keys) => key != undefined ? $(obj[key] || (obj[key] = {}), ...keys) : obj;
可用作:
const arr = [];
$(arr, 1, "testParent").testKey = "testValue";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.