0

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?

2
  • Do they have to be explicitly false? Would it be enough if they are "falsy" (like undefined)? Commented Nov 30, 2019 at 15:40
  • let a = b = c = d = 10; doesn't do what you think it does. It only creates one variable, a. Commented Nov 30, 2019 at 16:16

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.