I am trying extract an array that is inside an object in an array and I want to edit the value of the objects within that extracted array. It seems like this should be simple but I cant figure out why my forEach isnt updating the objects. From what I understand forEach mutates the original array so why isnt this working?
My expected result would be:
[
{
"label": "400 mg",
"value": "400 mg",
},
{
"label": "600 mg",
"value": "600 mg",
},
{
"label": "800 mg",
"value": "800 mg",
}
]
const array1 = [
{
"Name": "IBU (oral - tablet)",
"Strength": [
{
"Strength": "400 mg",
"NDC": "55111068201"
},
{
"Strength": "600 mg",
"NDC": "55111068301"
},
{
"Strength": "800 mg",
"NDC": "55111068401"
}
]
},
];
let newA = array1.map((item) => item.Strength).flatMap((item) => item)
newA.forEach((str) => ({label: str.Strength ,value: str.Strength}))
console.log(newA)
forEachmethod executes a provided function once for each array element without having anyreturn. In yourforEachyou create a newobjectwhich does not get used nor returned.newA.forEach((item) => {item.label = item.Strength})would change the initial object.