'How to update an Nested array using react hooks
PLZ help me, I'am stuck with problem now in my code
MY ARRAY IS
const Addons = [
{
id: 1,
SectionName: "AddOns",
items: [
{
id: 494,
name: "Cheese",
price: "1.0",
},
{
id: 434,
name: "Bacon",
price: 2.0,
},
{
id: 484,
name: "Onion",
price: 3.0,
},
],
},
{
id: 2,
SectionName: "BreadSelection",
items: [
{
id: 155,
name: "Wheat",
},
{
id: 165,
name: "Whole Grain",
},
],
},
{
id: 3,
SectionName: "Topping",
items: [
{
id: 175,
name: "Caremelized Onion",
},
{
id: 185,
name: "Tomatoes",
},
{
id: 195,
name: "Letues",
},
],
},
];
const [selectedOption, setSelectedOption] = useState("AddOns");
I just want to update the items array in the Addons so that there will be an new field in items array as follows
items: [
{
id: 175,
name: "Caremelized Onion",
checked:"true",
},
{
id: 185,
name: "Tomatoes",
},
{
id: 195,
name: "Letues",
},
],
a new object checked forms there
the main goal of this is the check un check items selected so if the item is selected the checked:"true" else checked:"false"
Solution 1:[1]
This should get a new Addons array such that each element in the items array will have a checked flag.
const newAddons = Addons.map(ad => ({
...ad,
items: ad.items.map(it => ({
...it,
checked: it?.checked || false
}))
}));
Explanation
- Use
.mapto iterate over theAddonsarray. - Spread existing props of addon
adfirst - Now, override
itemsprop usingad.items.map - For each element in the
itemsarray, addcheckedflag - If there is an existing
checkedflag, use the value; else, set it tofalse.
Code Snippet
const Addons = [
{
id: 1,
SectionName: "AddOns",
items: [
{
id: 494,
name: "Cheese",
price: "1.0",
},
{
id: 434,
name: "Bacon",
price: 2.0,
},
{
id: 484,
name: "Onion",
price: 3.0,
},
],
},
{
id: 2,
SectionName: "BreadSelection",
items: [
{
id: 155,
name: "Wheat",
},
{
id: 165,
name: "Whole Grain",
},
],
},
{
id: 3,
SectionName: "Topping",
items: [
{
id: 175,
name: "Caremelized Onion",
checked: true
},
{
id: 185,
name: "Tomatoes",
},
{
id: 195,
name: "Letues",
},
],
}
];
const newAddons = Addons.map(ad => ({
...ad,
items: ad.items.map(it => ({
...it,
checked: it.checked || false
}))
}));
console.log(newAddons)
Usage
When any option is selected/checked, use the Addons index (adIdx) and the corresponding item index (itIdx) to set the checked flag like so:
newAddons[adIdx][itIdx].checked = !newAddons[adIdx][itIdx].checked;
To directly update it on the state, use like so:
setAddons(prev => { prev[adIdx}[itIdx].checked = !prev[adIdx}[itIdx].checked); return prev });
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jsN00b |
