TransWikia.com

How can i remove object from nested array?

Stack Overflow Asked by Trajce12 on November 22, 2021

I have this kind of json.

let arr1 = [
    {
        "packageReference": "1234",
        "displayName": "Business",
        "description": "Includes...",
        "promotion": {
          "packageReference": "1234",
          "displayName": "$100 Standard",
          "optionGroup": [
            {
              "displayName": "Access",
            },
            {
              "displayName": "Contract"
            },
            {
              "displayName": "Equipment"
            },
            {
              "displayName": "Features"
            },
            {
              "displayName": "Fees",
            }
          ]
        }
      }
]

I need to remove only the object in the arr1[0].promotion.optionGroup where the displayName is ‘Fees’ and to return the new object without him.

2 Answers

// Get new array without the Fees one
const newGroup = arr1[0].promotion.optionGroup.filter(group => group.displayName !== 'Fees');

// Put new group into the object
arr1[0].promotion.optionGroup = newGroup;

Could also do it without creating a variable, but added it for cleanness.

Answered by Emre Koc on November 22, 2021

You could do it by filtering the sub array like so:

let arr1 = [
    {
        "packageReference": "1234",
        "displayName": "Business",
        "description": "Includes...",
        "promotion": {
          "packageReference": "1234",
          "displayName": "$100 Standard",
          "optionGroup": [
            {
              "displayName": "Access",
            },
            {
              "displayName": "Contract"
            },
            {
              "displayName": "Equipment"
            },
            {
              "displayName": "Features"
            },
            {
              "displayName": "Fees",
            }
          ]
        }
      }
];

arr1 = arr1.map(e => {
  e['promotion']['optionGroup'] = 
       e['promotion']['optionGroup'].filter(s => s['displayName'] != 'Fees');
  return e;
});


console.log(arr1);

Answered by MauriceNino on November 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP