繁体   English   中英

如何使用括号符号在对象文字上创建嵌套属性?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM