如果嵌套数组为空,如何删除对象。就像我有一个数组:
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'
]
}
]
答案 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;