在对象中创建动态键 [英] Creating Dynamic Keys In Object
问题描述
我正在努力在javascript中创建动态嵌套键.我的问题是我需要一个像这样的对象
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"
}
}
}
这里的问题是我需要从某个地方获取这些数据,并且需要动态创建这些值.道具的创建从第一级开始,一直到第四级.所以我的问题是如何在JS中创建动态密钥.我也知道您可以像这样在JS中创建动态键:
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.
有关上述对象的更多详细信息
在上面创建的对象中,我从数据库中获取数据,我需要动态添加 firstGrandFather,secondGrandFather,thirdGrandFather .而且我也不知道他们需要定义的孩子道具是什么.有些人可能里面有配偶,年龄,工作道具,有些人可能也不知道,我不知道会得到多少.这些继续进行一到两个级别.
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.
在php中,很容易在关联数组中轻松创建它们,但是我很难在JS中做到这一点.
In php it would be easy to create these in associative array easily but I am having hard time doing it in JS.
推荐答案
dynamic keys are possible in ES6+ Docs here
基本上,语法是:
obj[variable] = value;
变量必须包含原始值.
对于堆栈,恐怕您必须习惯使用点号或方括号表示法进行深度键访问.您还可以将对象的属性分配给变量,然后访问其属性.因此,如果obj是您示例中的对象:
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
它将分配以下内容:
{
first: 'AAA',
children: {
first: "AAAA"
}
}
这篇关于在对象中创建动态键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!