I need to modify component state which has inner array objects. There is no problem with modifying object array but I’d like to update inner object array value which has action format. It doesn’t update the action value as “No Action Needed”.
What’s the wrong with that map()
functions?
Thanks in advance.
let example_response = { data: [ { details: [ { format: "date", value: "2020-04-29T15:03:44.871Z", title: "Date" }, { format: "action", value: "-", title: "Action" } ], id: 13409, isSelected:true }, { details: [ { format: "date", value: "2019-04-29T15:03:44.871Z", title: "Date" }, { format: "action", value: "-", title: "Action" } ], id: 13409, isSelected:false } ] }; const newList = example_response.data.map((item) => { if (item.isSelected) { item.details.map((elem) => { if (elem.format === "action") { const updatedElem = { ...elem, value: "No Action Needed" }; return updatedElem; } }); } return item; }); console.log(newList);
Answer
I found 2 problems:
- You are not modifying
item.details
(you are just mapping it). - You only return
updatedElem
whenelem.format === "action"
but you’re returning anything otherwise
Try
let example_response = { data: [{ details: [{ format: "date", value: "2020-04-29T15:03:44.871Z", title: "Date" }, { format: "action", value: "-", title: "Action" } ], id: 13409, isSelected: true }, { details: [{ format: "date", value: "2019-04-29T15:03:44.871Z", title: "Date" }, { format: "action", value: "-", title: "Action" } ], id: 13409, isSelected: false }] }; const newList = example_response.data.map((item) => { if (item.isSelected) { item.details = item.details.map((elem) => { if (elem.format === "action") { elem.value = "No Action Needed"; } return elem; }); } return item; }); console.log(newList);