简体   繁体   中英

How to set all keys of object in Javascript to newValue without mutating (Redux)?

Question In JavaScript Form

I have an object like this:

const obj1 = {key1: value1, key2: value2, key3: value3, ...}

To change value of key1 (can be any key), this is my way:

const obj2 = {...obj1, key1: newValue}

I want to set all keys to some newValue , how to do it without mutation?
Wanted Output:

{key1: newValue, key2: newValue, key3: newValue, ...}

Question In Redux Form

I have my state like this:

{
  key1: value1,
  key2: value2,
  key3: value3,
  // ...
}

To change one value, I am doing like this in my reducer :

return {
  ...state,
  [action.key]: action.value
}

But how to change value of all the keys if I give some value through my action.value ? I want my next state like this:

{
  key1: newValue,
  key2: newValue,
  key3: newValue,
  // ...
}

You need to loop over keys, and create a new object using say reduce

 const obj = { key1: 1, key2: 2, key3: 3 } const value = 0; const updated = Object.keys(obj).reduce((acc, key) => (acc[key] = value, acc), {}) console.log(obj, updated)

Just for fun some proxy magic (do not use for production)

 const obj = { key1: 1, key2: 2, key3: 3 } const value = 0 const updated = {...new Proxy(obj, { keys() { return Object.keys(obj) }, get() { return value } }) } console.log(obj, updated)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM