简体   繁体   中英

Remove inner element from JSON array in Angular

I have the following JSON array.

[{
    "Group": "Title1",
    "subGroup": [{
        "name": "Test1",
        "id": 3
    }, {
        "name": "Hello",
        "id": 4
    }]
},
 {
    "Group": "Title2",
    "subGroup": [{
        "name": "Test2",
        "id": 5
    }, {
        "name": "Test2",
        "id": 6
    }]
}]

I want to remove the entire JSON object only if name = "Hello". I have the following code

  let deleteIndex=-1;
    MyData.forEach(sampleData => {
      deleteIndex = sampleData.subGroup.findIndex(data=> data.name === 'Hello');
      console.log(deleteIndex);
      delete sampleData.subGroup[deleteIndex];
    });
    console.log(JSON.stringify(MyData));
  }

Unfortunately, this is not working. I want data like this

 [{
        "Group": "Title1",
        "subGroup": [{
            "name": "Test1",
            "id": 3
        }]
    },
     {
        "Group": "Title2",
        "subGroup": [{
            "name": "Test2",
            "id": 5
        }, {
            "name": "Test2",
            "id": 6
        }]
    }]

Try using filter.

 const arr = [{ "Group": "Title1", "subGroup": [{ "name": "Test1", "id": 3 }, { "name": "Hello", "id": 4 }] }, { "Group": "Title2", "subGroup": [{ "name": "Test2", "id": 5 }, { "name": "Test2", "id": 6 }] }]; for (const item of arr) { item.subGroup = item.subGroup.filter(subitem => subitem.name !== 'Hello'); } console.log(arr);

I would use map and filter for this.

const newData = MyData.map(data => ({
   // spread the old data properties
   ...data,
   // for the subGroup array, only keep the ones where .name does not equal 'hello'
   subGroup: data.subGroup.filter(subData => subData.name !== 'hello'),
}));

console.log(newData);

You can simply do it using Array.map

 const input = [{ "Group": "Title1", "subGroup": [{ "name": "Test1", "id": 3 }, { "name": "Hello", "id": 4 }] }, { "Group": "Title2", "subGroup": [{ "name": "Test2", "id": 5 }, { "name": "Test2", "id": 6 }] }]; const output = input.map((item) => ({ Group: item.Group, subGroup: item.subGroup.filter(({ name }) => name !== 'Hello') })); console.log(output);

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