简体   繁体   中英

Conditionally change object property

I'm changing object property based on condition. I'm using react Let's say an object:

obj = {a: 4, b: 6, ...}

Now I want to change obj.a if flag is true so I can do something like below:

setState({...obj, a: flag === true ? 6 : obj.a})

Is there any other way to do it, I don't want to use ternary operator like above because in the nested object it looks nasty.

I also don't want to copy the object and change it like below:

 const obj_copy = {...obj}
 if(flag) obj_copy = 4;
 setState({...obj_copy))

Recently I came across the ?. which is really helpful.

// we can change this
obj && obj.a === 'text' ? ... : ...

// into
obj?.a === 'text' ? ... : ...

I'm looking for something like above... Just for knowledge purpose is there any way to do this?

You could a logical AND with the check and an object for spreading.

 let obj = { a: 4, b: 6 }, flag = true; console.log({...obj, ...flag === true && { a: 6 } }); flag = false; console.log({...obj, ...flag === true && { a: 6 } });

You could use Object.assign to conditionally assign the property like this:

setState(Object.assign({ ...obj }, flag === true ? { a: 6 } : {}))

Moreover, if flag is a boolean or you can accept any truthy value, I'd remove the equals signs:

setState(Object.assign({ ...obj }, flag ? { a: 6 } : {}))

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