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

163
Views
How to update nested object having array with useState in Reactjs?

Hello Developers how are you?

I am trying to update nested values, but all are failing.

const [ControlGaps, setControlGaps] = useState([
    {
      id: 1,
      name: "Pizza 1",
      status: 1,
      applicable: true,
      questions: [
        {
          id: 1,
          question:
            "how are you?",
          answer: null,
          evidence: null,
          treatment: null,
          type: "Implemented",
        {
          id: 2,
          evidence: null,
          treatment: null,
          type: "Implemented",
          question:
            "how old are you?",
          answer: null,
         }
      ],
    },
    {
      id: 2,
      name: "Pizza 2",
      status: 1,
      applicable: true,
      questions: [
        {
          id: 1,
          type: "Implemented",

          question:
            "How are you 2?",
          answer: null,
          evidence: null,
          treatment: null,
         
        {
          id: 2,
          answer: null,
          evidence: null,
          treatment: null,
          type: "Implemented",
          question:
            "How old are you?",
        },
      ],
    }])

I tried to use onChange this

    setControlGaps([...ControlGaps, [ControlGaps[index]].applicable]:checked]);

or

    setControlGaps({
      ...ControlGaps,
      [ControlGaps[index].applicable]: checked,
    });

But it's all wrong.

The question is how to update values in nested field like updating fields in object inside array of objects for example.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Can be done using some slice() and spread. But you should look at immutability helpers for such nested stuff.

setControlGaps([setControlGaps.slice(0,index),
{ ...ControlGaps[index],
 applicable : checked
}
,setControlGaps.slice(index+1)]);
about 4 years ago · Juan Pablo Isaza Report

0

Try this

setControlGaps(prevState => {
    const newState = prevState.map((item, itemIndex) => {
        if (itemIndex === index) {
            item.applicable = false;
            return item;
        }
        return item;
    });
    return newState;
});
about 4 years ago · Juan Pablo Isaza 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!