1

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;
JAN
  • 21,236
  • 66
  • 181
  • 318
  • 4
    `const obj = {}; ['w','a','s','d'].forEach(x=>obj[x]=true);` Does it work? Sure... Is it better? Heck no. – Cerbrus Nov 11 '22 at 11:41
  • Lots of ways, depending on your precise requirements. Does the object already exist, or are you creating a new object? – Ben Aston Nov 11 '22 at 11:41
  • Is this `Object.keys(obj).forEach(k => obj[k] = true) ` meet your demand? – flyingfox Nov 11 '22 at 11:41
  • @lucumt how are there any keys on `obj`? Are we assuming `obj` already exists? – Cerbrus Nov 11 '22 at 11:42
  • @Cerbrus So OP needs to make his question more specific – flyingfox Nov 11 '22 at 11:44
  • Duplicate of: [How do I loop through or enumerate a JavaScript object?](https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object) – Cerbrus Nov 11 '22 at 11:48

3 Answers3

1

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))
Ben Aston
  • 53,718
  • 65
  • 205
  • 331
1

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);
Andrew Parks
  • 6,358
  • 2
  • 12
  • 27
  • Well, sure, but what do you think the chance is that that ain't example data? – Cerbrus Nov 11 '22 at 11:49
  • @Cerbrus since `wasd` maps to common left,right,up,down keyboard navigation characters, I made the assumption this has to do with keyboard characters. It's not a bad assumption until the OP clarifies their intent :) – Andrew Parks Nov 11 '22 at 11:50
  • So the question is unclear. That doesn't need an answer, it needs clarification or a close-vote. – Cerbrus Nov 11 '22 at 11:51
-1

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);
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39