如果在Typescript中数组为空,则从嵌套数组中删除对象

时间:2017-12-18 12:38:53

标签: arrays angular typescript

如果嵌套数组为空,如何删除对象。就像我有一个数组:

pokemonGroups = [
    {
      name: 'Grass',
      pokemon: [
        'bulbasaur-0', 'Bulbasaur', 'oddish-1','Oddish','bellsprout-2', 'Bellsprout'
      ]
    },
    {
      name: 'Water',
      pokemon: [

      ]
    }]

所以在这里我们有一个空数组

{
   name: 'Water',
   pokemon: []
}

所以我想删除这个对象,我的数组应该是:

pokemonGroups = [
    {
      name: 'Grass',
      pokemon: [
        'bulbasaur-0', 'Bulbasaur', 'oddish-1','Oddish','bellsprout-2', 'Bellsprout'
      ]
    }
 ]

2 个答案:

答案 0 :(得分:1)

您可以使用过滤器:

pokemonGroups = pokemonGroups.filter(group => group.pokemon.length != 0);

答案 1 :(得分:1)

您可以迭代数组并使用array.splice()



var pokemonGroups = [{
    name: 'Grass',
    pokemon: [
      'bulbasaur-0', 'Bulbasaur', 'oddish-1', 'Oddish', 'bellsprout-2', 'Bellsprout'
    ]
  },
  {
    name: 'Water',
    pokemon: [

    ]
  }
]

for (var i = 0; i < pokemonGroups.length; i++) {
  if (pokemonGroups[i]['pokemon'].length == 0) {
    pokemonGroups.splice(i, 1);
  }
}

console.log(pokemonGroups)
&#13;
&#13;
&#13;