简体   繁体   中英

How can i remove object from nested array?

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.

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);

// 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM