Home > OS >  Changing the values inside an object within an array
Changing the values inside an object within an array

Time:09-16

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)

CodePudding user response:

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.map((str) => {
  str.label= str.Strength ;
  str.value = str.Strength;
  delete str.Strength;
  delete str.NDC
})
console.log(newA)

CodePudding user response:

I assume that you are looking for this, using .map not .forEach.

const result = [
        {
            "Name": "IBU (oral - tablet)",
            "Strength": [
                {
                    "Strength": "400 mg",
                    "NDC": "55111068201"
                },
                {
                    "Strength": "600 mg",
                    "NDC": "55111068301"
                },
                {
                    "Strength": "800 mg",
                    "NDC": "55111068401"
                }
            ]
        }    
][0].Strength.map(el => ({ label: el.Strength, value: el.Strength }));

console.log(result);

  • Related