This question already has an answer here:
这个问题在这里已有答案:
- Object with another's object's property as a key 1 answer
将另一个对象的属性作为关键1答案
Subs.find({ }).forEach(function(div){
var sub_type = div.type ;
var sub_TO = div.text ;
var man = div.arn;
var obj = {man: []};
obj.man.push({"type": sub_type, "TO" :sub_TO});
var json = JSON.stringify(obj);
console.log(json);
})
here is my problem I want man
who is in obj
to be a variable and change each time the forEach()
runs and i don't understand why when i log the obj
i see man instead of the value my variable.
这是我的问题我希望obj中的人变成一个变量并且每次运行时更改forEach()并且我不明白为什么当我记录obj时我看到man而不是值my变量。
An other question. if it is posible to use a variable for the man
how should i do the line obj.man.push({"type": sub_type, "TO" :sub_TO});
?
另一个问题。如果可以为男人使用变量,我应该怎么做obj.man.push行({“type”:sub_type,“TO”:sub_TO}); ?
1 个解决方案
#1
2
You can use new initializer syntax that lets you use an expression for the key. Use square brackets for this:
您可以使用新的初始化程序语法,该语法允许您使用表达式作为键。使用方括号:
var obj = {[man]: []};
Or for legacy browsers, create the object first, then use the brackets to evaluate the expression.
或者对于旧版浏览器,首先创建对象,然后使用括号来计算表达式。
var obj = {};
obj[man] = [];
Then use the typical square brackets when accessing the property.
然后在访问该属性时使用典型的方括号。
obj[man].push({"type": sub_type, "TO" :sub_TO});
#1
2
You can use new initializer syntax that lets you use an expression for the key. Use square brackets for this:
您可以使用新的初始化程序语法,该语法允许您使用表达式作为键。使用方括号:
var obj = {[man]: []};
Or for legacy browsers, create the object first, then use the brackets to evaluate the expression.
或者对于旧版浏览器,首先创建对象,然后使用括号来计算表达式。
var obj = {};
obj[man] = [];
Then use the typical square brackets when accessing the property.
然后在访问该属性时使用典型的方括号。
obj[man].push({"type": sub_type, "TO" :sub_TO});