Creating Dynamic Keys In Object

烂漫一生 提交于 2021-02-08 07:32:11

问题


I am struggling to create dynamic nested keys in javascript. My problem is that I need to have a object like this

{
    "grandGrandFather": 'A',
    "firstGrandFather": {
        name: "AA",
        children: {
            first: 'AAA',
            children: {
                first: "AAAA"
                }
            }
        }, 
    "secondGrandFather": {
        name: "AB",
        first: 'ABA',
            children: {
                first: "ABAA",
                second: "ABAB"
                }
            }
        }, 
    "thirdGrandFather": {
        name: "AC",
        children: {
            name: "ACA"

            }
        }     
}

Here problem is that I need to fetch these data from somewhere and I need to create these values dynamically. The prop creation begins from the first level and goes upto fourth level. So my question is how can I create dynamic keys in JS. Also I know you can create dynamic keys in JS like this:

var obj = {
    prop1: "a",
    prop2: "b",
   prop3:'c'

}
obj['prop4'] = 'd';

Also I have been successful in creating a props to a level but when I need to stack these I get confused any help would be appreciated.

Further details about above object

In the above object I created I am getting data from database and I need to add firstGrandFather, secondGrandFather, thirdGrandFather dynamically. Also I don't know what their children props I need to define would be in the object. Some may have spouse,age,work props inside some may not also I don't know how many of these I would get. And these goes on for one or two more level.

In php it would be easy to create these in associative array easily but I am having hard time doing it in JS.


回答1:


dynamic keys are possible in ES6+ Docs here

Basically, the syntax is:

obj[variable] = value;

Variable must contain a primitive value.


As for stacking, I'm afraid you have to get used to working with deep keys access with either dot or bracket notation. You can also assign a property of your object to a variable and then access its props. So if obj is the object from your example:

const firstGrandfathersChildren = obj.firstGrandFather.children

It will have the following assigned:

{
    first: 'AAA',
        children: {
            first: "AAAA"
        }
}


来源:https://stackoverflow.com/questions/53460072/creating-dynamic-keys-in-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!