Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
How to update the data inside the nested Array

I have data structure like this:

const data = [
  {
    question: 'string of question',
    parentId: '1',
    userChoice: 'Yes',
    child: []
  },
  {
    question: 'string of question',
    parentId: '2',
    userChoice: 'No',
    child: [
      {
        id: 6,
        sub_question: 'sub question',
        weightage: 1
      },
      {
        id: 7,
        sub_question: 'sub question',

        weightage: 1
      },
      {
        id: 8,
        sub_question: 'sub question',
        weightage: 1
      }
    ]
  }
]

I'm able to handle the first layer of data without child array.

This is how I'm doing;

  // states
  const deviceReport = localStorage.getItem('deviceReport') ? JSON.parse(localStorage.getItem('deviceReport')) : []
  const [data, setData] = useState(deviceReport)
  const [childData, setChildData] = useState([])

// To Put user response via question param to data and then persist it with localStorage
const handleClickYes = (question) => {
    // find if question is in the data array
    const hasQuestion = data.find(({ parentId }) => question.id === parentId)

    const indexOfQuestion = data.indexOf(hasQuestion)

    // copy data to mutable object
    let newData = [...data]
    if (hasQuestion) {
      // update the value with specific selected index in the array.
      newData[indexOfQuestion] = {
        question: question.if_yes,
        parentId: question.id,
        userChoice: 'YES',
        child: []
      }
    } else {
      //   concat existing data with a new question
      newData = [
        ...newData,
        {
          question: question.if_yes,
          parentId: question.id,
          userChoice: 'YES',
          child: []
        }
      ]
    }
    localStorage.setItem('deviceReport', JSON.stringify(newData))
    setData(newData)
  }

Similary Now I want to add the data into child array with similar logic like If child array has same key then it should not concate otherwise it should concate the child array

I tried following this method to build childData first then concate into data.child[] But this is not working even to collect the user response

    function subQuestionsHandler(sub) {
      // const hasId = data.child.some(({ id }) => sub.id === id)
      const id = sub.id
      const sub_question = sub.sub_question
      const weightage = sub.weightage
      // console.log(id, sub_question, weightage)

      const hasId = childData.find(({ id }) => sub.id === id)

      if (!hasId) {
        setChildData((childData) => childData.concat({ id: id, sub_question: sub_question, weightage: weightage }))
        
      }
    }

So how can I concate the child array inside the data array. ?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Array:

let data = [
  {
    id: 1,
    question: "...",
    children: [],
  },
  {
    id: 2,
    question: "...",
    children: [
      {
        id: 1,
        sub_question: "...",
      },
      {
        id: 2,
        sub_question: "...",
      },
    ],
  },
];

Concat array:

data = [...data];

data.push({
  id: 3,
  question: "concatenated",
  children: [],
});

Update array:

const datumIndexToUpdate = 0;

data = [...data];
data[datumIndexToUpdate] = { ...data[datumIndexToUpdate] };

data[datumIndexToUpdate].question = "updated";

Concat sub-array:

const datumIndexToUpdate = 0;

data = [...data];
data[datumIndexToUpdate] = { ...data[datumIndexToUpdate] };
data[datumIndexToUpdate].children = [...data[datumIndexToUpdate].children];

data[datumIndexToUpdate].children.push({
  id: 3,
  sub_question: "concatenated",
});

Update sub-array:

const datumIndexToUpdate = 0;
const childIndexToUpdate = 0;

data = [...data];
data[datumIndexToUpdate] = { ...data[datumIndexToUpdate] };
data[datumIndexToUpdate].children = [...data[datumIndexToUpdate].children];
data[datumIndexToUpdate].children[childIndexToUpdate] = {
  ...data[datumIndexToUpdate].children[childIndexToUpdate],
};

data[datumIndexToUpdate].children[childIndexToUpdate].sub_question = "updated";
about 4 years ago · Juan Pablo Isaza Denunciar

0

This is how you concat an array

[1].concat([3]) === [1, 3]

This is how you concat a nested array

const nest1 = [[1]]
const nest3 = [[3]]
nest3[0].concat(nest1[0]) // === [[3, 1]]

Now I suggest simplifying your scenario and applying this logic to it. Or change the title in your question

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda