Home > database >  How to update the data inside the nested Array
How to update the data inside the nested Array

Time:03-26

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. ?

CodePudding user response:

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

CodePudding user response:

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";
  • Related