I have a state:
const obj = [{id: "1", obj_of_names: [{
id: "a1",
name: "abc",
school: "xyz" },
{ id:"b1",
name: "def",
school: "zyx" },
{ id:"c1",
name: "ghi",
school: "pqr" }]
},
{id: "2", obj_of_names: [{
id: "d1",
name: "abc123",
school: "xyz123" }]
}]
const [newobj, setObj] = useState("obj")
Now I want to update school for the id:d1 inside id:2. Suppose the old value is school: xyz123 now I want to update it to school: newxyz123. How can I achieve this using the spread operator or by another method?
I tried the below code:
setObj((prevObjects) => {
const tempIndex = prevObjects.findIndex(
(item) => item.id === reqdImgID
);
const newObject = obj[tempIndex].obj_of_names.map((obj) => {
if (obj.id == reqdID) {
return { ...obj,
school: newSchool,};}
return obj; }););
But I am getting this as an ouput: { id:"c1", name: "ghi", school: "newxyz123" }