Is there a way to assign values to multiple keys of an object without repeating the object name?
For example: We have this object created:
var obj = {
"a": 0,
"b": 0,
"c": 0,
"d": 0
}
What i want now is to assign values to some or all keys of this object which is already created(you would normally do it like this):
obj["a"] = yourValue;
obj["c"] = yourValue;
obj["d"] = yourValue;
but without repeating the object name as i did above.
Would there be a way to do such thing?
You could use Object.assign and map the wanted keys with the values as object for an update with the wanted value.
var object = { a: 0, b: 0, c: 0, d: 0 },
value = 42,
keys = ['a', 'c', 'd'];
Object.assign(object, ...keys.map(k => ({ [k]: value })));
console.log(object);
ES5
var object = { a: 0, b: 0, c: 0, d: 0 },
value = 42,
keys = ['a', 'c', 'd'];
keys.forEach(function (k) {
object[k] = value;
});
console.log(object);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With