Home > Software design >  spread two different objects with ternary
spread two different objects with ternary

Time:07-17

I have the following code and I want to manipulate sate under certain condition how to add the targeted state to the state object ? I tried tow options none has worked

const trueArr = { a: true, b: true, c:true };
const falseArr ={ a: false, b: false, c: false };
    
    setSate({
      ...iniciSate,
     [foo == 'test'  ? trueArr : falseArr]
    });
    
    
    setSate({
      ...iniciSate,
     {foo == 'test' ? ...trueArr : ...falseArr}
    });

CodePudding user response:

You were very close:

setSate({
  ...iniciSate,
 (foo == 'test') ? ...trueArr : ...falseArr
});

CodePudding user response:

This is a javascript question and not React.

To conditionally add this or that object's properties to another (using spread):

const state = {x:1}
const trueArr = { a: true, b: true, c:true }
const falseArr ={ a: false, b: false, c: false }

console.log(
    {...state, ...(true ? trueArr : falseArr)},

    // or "false"

    {...state, ...(false ? trueArr : falseArr)}
)

When you write ...(true ? trueArr : falseArr), then the surrounding parentheses evaluates it first, so the spread operator (...) "knows" which of the two options it applies to (the evaluated result)

  • Related