cat*_*ple 0 javascript frontend data-structures
我想从两个数组中获得一个对象,我是按照以下方式完成的.
for (var j = 0; j < rawDataRows.length; j++) {
for (var i = 0; i < categories.length; i++) {
var category = categories[i];
var rowValue = rawDataRows[j];
// here I do got the right value for category
console.log(category);
console.log(rowValue);
// but the following line doesn't interpret category as a variable
formattedDataRows.push({category: rowValue});
}
}
Run Code Online (Sandbox Code Playgroud)
我假设我可以得到类似的东西:
[{"category1": "value1"},{"category2": "value2"}, {"category3": "value3"}]
Run Code Online (Sandbox Code Playgroud)
然而,事实证明我得到了:
[{"category": "value1"}, {"category": "value2"}, {"category": "value3"}]
Run Code Online (Sandbox Code Playgroud)
谁能指出我错在哪里?此外,如果您有更好的方法来实现目标,请发表评论.Javascript只有jQuery或其他框架.谢谢!
小智 5
对象文字语法在ECMAScript 5及更低版本中,您不允许将变量标识符指定为属性名称.而是首先创建对象,然后使用括号表示法.
var o = {};
o[category] = rowValue;
formattedDataRows.push(o);
Run Code Online (Sandbox Code Playgroud)
使用ECMAScript 6,您可以执行以下操作:
formattedDataRows.push({[category]: rowValue});
Run Code Online (Sandbox Code Playgroud)
虽然当然对语法的支持是有限的.
| 归档时间: |
|
| 查看次数: |
39 次 |
| 最近记录: |