Reputation: 9
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
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
Reputation: 3644
There are several methods of doing this,
Object.entries
const test = {
a: "somestring",
b: 42
};
// Using Object.entries
for (let [key] of Object.entries(test)) {
test[key] = false
}
console.log(test);
Object.keys
const test = {
a: "somestring",
b: 42
};
// Using Object.keys
Object.keys(test).forEach(key => {
test[key] = false;
})
console.log(test);
for ... in
const test = {
a: "somestring",
b: 42
};
// Using for ... in
for (key in test) {
test[key] = false;
}
console.log(test);
Upvotes: 1
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