harish kumar
harish kumar

Reputation: 1759

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?

Upvotes: 1

Views: 2024

Answers (2)

virgiliogm
virgiliogm

Reputation: 976

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 } : {}))

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386570

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

Upvotes: 1

Related Questions