Is there a way to set multiple object properties to one value in JavaScript?

I know that you can do let a = b = c = d = 10;

but when I have values in object like so let key = {w : false, a : false, s : false, d : false};

can I somehow set all values to false at once? I couldnt find answer. I tried something like

let key = {w,a,s,d => false}; let key = {w : a : s : d : false}; let key = {w,a,s,d : false};

Is it possible to do something like this in js?

Upvotes: 0

Views: 2184

Answers (3)

roberto tomás
roberto tomás

Reputation: 4687

just because it is fun, you can also use a proxy:

sycophant = new Proxy({}, {get () { return false }})
proxyConstruct = (keys, proxy = sycophant) => 
    Object.fromEntries(keys.map(key => ([key, proxy[key]])))

falsyAThroughD = proxyConstruct(['a','b','c','d'])

incrementingAThroughD = (() => {
  base = {x:0}
  return proxyConstruct(['a','b','c','d'], 
    new Proxy(base, {get (target) { return target.x++ }}))
})()

edit: kinda surprised this "defaultdict" kind of approach earned no love

Upvotes: 0

junwen-k
junwen-k

Reputation: 3644

There are several methods of doing this,

Method 1: Object.entries

const test = {
  a: "somestring",
  b: 42
};

// Using Object.entries
for (let [key] of Object.entries(test)) {
  test[key] = false
}

console.log(test);

Method 2: Object.keys

const test = {
  a: "somestring",
  b: 42
};

// Using Object.keys
Object.keys(test).forEach(key => {
  test[key] = false;
}) 

console.log(test);

Method 3: for ... in

const test = {
  a: "somestring",
  b: 42
};

// Using for ... in
for (key in test) {
  test[key] = false;
}

console.log(test);

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191936

You can manually set the values in a chain:

const obj = {};

obj.w = obj.a = obj.s = obj.d = false;

console.log(obj)

You can iterate the array of keys with Array.forEach(), and set the values:

const updateObj = (value, keys, obj) =>
  keys.forEach(k => obj[k] = value)  

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

updateObj(false, Object.keys(obj), obj);

console.log(obj)

updateObj(true, ['w', 's'], obj);

console.log(obj)

Upvotes: 2

Related Questions