Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning values to multiple keys without repeating the object name

Tags:

javascript

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?

like image 576
user3477993 Avatar asked Oct 19 '25 02:10

user3477993


1 Answers

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);
like image 143
Nina Scholz Avatar answered Oct 21 '25 15:10

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!