我有一个这样的数组:
rules[0] = "a";
rules[1] = "b";
rules[2] = "c";
对象data
的值为value-a
,value-b
,value-c
(最后一个字母来自"规则"。
我知道你可能会建议一个数组,但我真的需要它们作为普通属性。如何创建这些由字符串" value - "形成的动态属性名称。和变量的值?
for r in rules {
data.value-??? = "something";
}
答案 0 :(得分:3)
试试这个:
const data = rules.reduce((dict, key) => {
dict[`value-${key}`] = 'something';
return dict;
}, {});
答案 1 :(得分:1)
您可以使用for ... of
语句,该语句使用元素
var rules = ["a", "b", "c"],
data = {};
for (let r of rules) {
data['value-' + r] = "something";
}
console.log(data);
ES6
var rules = ["a", "b", "c"],
data = {};
rules.forEach(r => data['value-' + r] = "something");
console.log(data);
ES5
var rules = ["a", "b", "c"],
data = {};
rules.forEach(function (r) {
data['value-' + r] = "something"
});
console.log(data);
答案 2 :(得分:1)
试试这个:
var data = {};
var rules = ['a', 'b', 'c', 'd'];
rules.forEach(function(rule) {
data['value-'+rule] = "something";
});
console.log(data);