I have below mock data based on object property need to update their respective value using spread operator. I am not able to do that because it is nested.
I am able to achieve using below approach but as you can see code line is getting increased. But we can definitely reduce use spread operator. Because in "title" property i am only updating 0 index and in left column only updating the label value rest of the thing is same.
const mockData = {
title: ["Javascript", "Selected Topic"],
leftColumn: [
{
key: "name",
label: "Javascript Topic Name",
type: "string",
},
{
key: "id",
label: "Javasctipt Topic Id",
type: "string",
},
],
};
const handleType = (val) => {
switch (val.type) {
case "Javascript":
return {
...mockData,
};
case "Angular":
return {
...mockData,
title: ["Angular", "Selected Topic"],
leftColumn: [
{
key: "name",
label: "Angular Topic Name",
type: "string",
},
{
key: "id",
label: "Angular Topic Id",
type: "string",
},
],
};
case "React":
return {
...mockData,
title: ["React", "Selected Topic"],
leftColumn: [
{
key: "name",
label: "React Topic Name",
type: "string",
},
{
key: "id",
label: "Reacr Topic Id",
type: "string",
},
],
};
}
};
i am trying something below approach but not getting desired result
const handleType = (val) => {
const newArray = [mockData];
console.log("newArray", newArray);
// const index = mockData.findIndex((ele) => ele);
// console.log("index", index);
// newArray["title"][0] = "React";
// console.log("newArray ==>", newArray);
switch (val.type) {
case "Javascript":
return {
...mockData,
};
case "Angular":
mockData.title[0] = "Angular";
return mockData.leftColumn.map((val, index) => {
let value = { ...val, label: "Angular",};
return Object.assign({}, value);
});
case "React":
return {
...mockData,
title: ["React", "Selected Topic"],
leftColumn: [
{
key: "name",
label: "React Topic Name",
type: "string",
},
{
key: "id",
label: "Reacr Topic Id",
type: "string",
},
],
};
}
};
const type = {
type: "Angular",
};
console.log("Angular", handleType(type));
question from:
https://stackoverflow.com/questions/65844124/how-update-the-nested-property-in-object-i-e-object-also-containing-array-of-ob