Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

90
Views
spread two different objects with ternary

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

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

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)

about 4 years ago · Santiago Gelvez Report

0

You were very close:

setSate({
  ...iniciSate,
 (foo == 'test') ? ...trueArr : ...falseArr
});
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!