Home > Blockchain >  How to update nested array of objects in ReactJS
How to update nested array of objects in ReactJS

Time:07-04

I have an array of object like this:

const tempobj = [
{
    id: "1",
    fanimate: [
        {
            id: "111",
            animate: "xyz",
        },
    ],
},];

Now I want to add more animations inside this array, such that each object gets added in the fanimate such that:

const tempobj = [
{
    id: "1",
    fanimate: [
        {
            id: "111",
            animate: "xyz",
        },
        {
            id: "222",
            animate: "def",
        },
    ],
},];

I tried using the hook useState, but I am getting undefined results

CodePudding user response:

const tempobj = [
{
    id: "1",
    fanimate: [
        {
            id: "111",
            animate: "xyz",
        },
    ],
}];

const modified = tempobj.map(temp => {
  const newtemp = {
    id: temp.id,
    fanimate: [...temp.fanimate, {id:"222", animate:"def"}]
  }
  return newtemp;
})

console.log(modified);

CodePudding user response:

You could just spread all the places

const tempObj = {
id:'1',
fan:[
{
  id:'2',
  animate:'xyz'
}
]
}



console.log(tempObj)

 const newtest={...testObj,fan:[...testObj.fan, {id:'3', animate:'tuz'}]}

 console.log(newtest)

CodePudding user response:

Try this:

const tempobj = [
  {
    id: "1",
    fanimate: [
      {
        id: "111",
        animate: "xyz"
      }
    ]
  }
];

const [state, setState] = useState(tempobj);

function updateArray(newItem) {
  setState(
    state.map((i) => ({ id: i.id, fanimate: [...i.fanimate, newItem] }))
  );
}

You can push the newItem to the original fanimate array using spread operator, everytime a new item is added, the original array data is copied by ...i.fanimate:

{ id: i.id, fanimate: [...i.fanimate, newItem] } 

BTW the naming of tempobj really should be tempArr or tempArray, although technically javascript array is a special type of object.

A working sandbox

  • Related