1

I have an array like this:

rules[0] = "a";
rules[1] = "b";
rules[2] = "c";

And an object data that has values value-a, value-b, value-c (the last letter comes from "rules".

I know you might suggest an array, but I really need them to be normal attributes. How can I create these dynamic attribute names formed with the string "value-" and the value of a variable?

for r in rules {
  data.value-??? = "something";
}
1
  • 2
    data["value-" + r] = "something" Commented Jan 17, 2017 at 17:45

3 Answers 3

2

Try this:

const data = rules.reduce((dict, key) => {
    dict[`value-${key}`] = 'something';
    return dict;
}, {});
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

var data = {};
var rules = ['a', 'b', 'c', 'd'];
rules.forEach(function(rule) {
  data['value-'+rule] = "something";
});
console.log(data);

Comments

0

You could use for ... of statement, which uses the element

var rules = ["a", "b", "c"],
    data = {};

for (let r of rules) {
    data['value-' + r] = "something";
}
console.log(data);

Or simple Array#forEach

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.