• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

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

almost 3 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)

almost 3 years ago · Santiago Gelvez Report

0

You were very close:

setSate({
  ...iniciSate,
 (foo == 'test') ? ...trueArr : ...falseArr
});
almost 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error