Home > Software design >  How do I update one of the array fields?
How do I update one of the array fields?

Time:09-27

I have an array like this:

a=[{id:1 , operand:2 ,children:[{a:1]{b:2}]

And I do this when I want to add a new field:

   const [items, setItems] = useState(a);
    
      const gettableData = (value) => {
        let operanList = items;
  let repeatListError = tableData.filter((i) => i.operandId === value.operandId);
    if (!repeatListError.length > 0) operanList.push(value);
        setTableData(operanList);
      };

This method is called every time I click a button. I want to check operand when I add a new object, if there is only update children.like:

value=[{id:1 , operand:2 ,children:[{a:1]{b:2}{c:3}{d:4}]

CodePudding user response:

First reformat value like the following.What you have is incorrect in syntax:

  const value=[{id:1 , operand:2 ,children:{a:1,b:2,c:3,d:4}}]

This how you can change the children inside the objects that are in your array:

  const list = [
    { id: 1, operand: 2, children: { a: 1, b: 2, c: 3, d: 4 } },
    { id: 2, operand: 3, children: { a: 1, b: 2, c: 3, d: 4 } },
  ];

  let newList = [...list];
  let updatedChildren = { ...newList[1].children, e: 5, f: 6 };
  let updatedItem = { ...newList[1], children: updatedChildren };
  newList.splice(1, 1, updatedItem);

  console.log(newList);

  setState(newList);

you create a new instance of the array. update the children attribute of your desired item ( in this case i chose 1 ). then update the entire object that is in your array ( it contains the id & operand and children ). and finally mutate the newList with replacing the original item by the new one. In the splice method remember the second number must always be one, as it will remove one item and the first number given should be the index of the item that is needed to be changed ( in this case we chose one). then you can continue with setting the state as you wish since you have a new, updated list.

CodePudding user response:

You have to put the array in another variable and tell it that if it has children, it will remember it in the children field and set a new value for it.

  • Related