简体   繁体   English

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

[英]How do I create nested properties on object literals using bracket notation?

The following works but I'm trying to find a way to omit the arrayOfObjects[1]['testParent'] = {} bit, imagine you wanted to add a value to an empty object that is nested 10 levels down, you would have to initialize each level with an empty {} first, I'm trying to find a workaround for that. 下面的作品,但我试图找到一种方法来省略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'
    }
 };

In fact, you can avoid the array indexer as well with something like: 实际上,您也可以避免使用数组索引器:

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

You can create custom method for this, using reduce that takes string and value and sets nested property. 您可以为此创建自定义方法,方法是使用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) 

Maybe a small helper can help you to omit the brackets: 也许一个小帮手可以帮助您省略括号:

const $ = (obj, key, ...keys) => key != undefined ? $(obj[key] || (obj[key] = {}), ...keys) : obj;

Usable as: 可用作:

const arr = [];
$(arr, 1, "testParent").testKey = "testValue";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 仅使用属性访问器(点符号或方括号符号),如何直接设置未定义的嵌套属性? - Using only property accessors (dot notation or bracket notation), how do I set undefined nested properties directly? 使用括号符号访问对象中的属性 - Accessing Properties in object using bracket notation 使用功能和括号符号将属性添加到对象 - Adding properties to an object using function and bracket notation javascript中使用方括号表示法的嵌套对象 - Nested object using square bracket notation in javascript jsdoc:如何使用括号表示法记录属性? - jsdoc: how to document properties using bracket notation? 无法使用“ .nested”标志和括号表示法检查嵌套对象的属性 - Unable to check a nested object property by using the “.nested” flag and bracket notation 如何使用方括号表示法使用多个变量来调用嵌套对象? - How do I use Square Bracket Notation to use multiple variables to call nested objects? 如何使用模板文字从 JSON 数据创建嵌套“列表”? - How do I create a nested "list" from JSON data by using template literals? 使用括号表示法构建一个新的嵌套 object - build a new nested object with bracket notation 访问对象属性时,括号表示法是否比句点表示法慢? - Is bracket notation slower than period notation for accessing Object properties?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM