JAN
JAN

Reputation: 21865

Set multiple properties at the same time instead of line by line

Consider:

const obj = {
  w: true,
  a: true,
  s: true,
  d: true
};

Can we set all properties at once without repeating true every line ?

And not something like this:

let obj = {};
obj.a = obj.w = obj.d = obj.w = true;

Upvotes: 1

Views: 64

Answers (3)

Andrew Parks
Andrew Parks

Reputation: 8087

If you have single-letter properties that you'd like to set at once, you can do:

const obj = Object.fromEntries([...'wasd'].map(i=>[i,true]));
console.log(obj);

If you have other properties in the object you want to set as well, you can do:

const obj = {
  hello: 1,
  world: '!',
  ...Object.fromEntries([...'wasd'].map(i=>[i,true]))
}
console.log(obj);

Upvotes: 1

Ben Aston
Ben Aston

Reputation: 55739

Here's one way using Object.fromEntries 👇

const o = Object.fromEntries(['w', 'a', 's', 'd'].map((v) => [v, true]))
console.log(o)

...or if the object already exists and you want to change a subset 👇

const setProps = (o, propNames, value) => 
    (propNames.forEach((prop) => o[prop] = value), o)

const o = {'a': false, 'b': false, 'c': false }
console.log(setProps(o, ['a', 'b'], true))

Upvotes: 1

Tushar Shahi
Tushar Shahi

Reputation: 20461

If it is actually useful to you, you can make an impure function that takes your object and modifies and returns it.

const addMultipleSameProperties = (obj,keys = [],val = undefined) => {
keys.forEach((x) => {
 obj[x] = val 
});
};

let obj = {};
addMultipleSameProperties(obj,['a','w','d'],true);
console.log(obj);

Upvotes: -1

Related Questions