【问题标题】:Javascript: delete object from array based on value inside object [duplicate]Javascript:根据对象内部的值从数组中删除对象[重复]
【发布时间】:2019-10-26 03:30:10
【问题描述】:

我已经建立了一个数组对象结构如下

nestedArray = [ { source : "a" , target : "b", table : "ab" }, 
{ source : "c" , target : "d", table : "cd" }, 
{ source : "a" , target : "d", table : "cd" }, 
{ source : "a" , target : "f", table : "cd" }];

我写了下面的代码来删除source是a的所有嵌套对象。


nestedArray.forEach(function(element) {
  if(element.source == "a") {
    nestedArray.splice(nestedArray.indexOf(element), 1) ;
  }
});

但是当我尝试在上面的代码之后打印数组时,我仍然可以看到source 为a 的对象。

> > nestedArray 
[ { source: 'c', target: 'd', table: 'cd' },  
 { source: 'a', target: 'f', table: 'cd' } ]
> >

我在这里遗漏了什么吗?任何建议都非常感谢。

【问题讨论】:

  • 使用filter() 而不是forEach()。

标签: javascript


【解决方案1】:

为什么我的代码不起作用?

使用splice,您正在改变原始数组,这会改变您正在循环的数组的长度,然后您会跳过一些索引,即

  • 第一个匹配在索引0,所以当你拼接剩余元素索引时,它会减少1,但是因为你已经在同一个数组上循环,所以index循环的值设置为@987654325 @迭代后
  • 现在1 处的元素是{source: 'a'...} 而不是{source: c} 所以现在当我们再次拼接时,索引减少了1 和index 循环的值在迭代后设置为2
  • 所以现在在索引 2 上,但在那个特定索引上没有任何价值

你可以简单地使用过滤器

let nestedArray = [ { source : "a" , target : "b", table : "ab" }, 
{ source : "c" , target : "d", table : "cd" }, 
{ source : "a" , target : "d", table : "cd" }, 
{ source : "a" , target : "f", table : "cd" }];

let op = nestedArray.filter(({source})=> source !== 'a')

console.log(op)

【讨论】:

  • @TylerRoper 我已添加,但试图为它形成更好的解释
  • 别担心,很好的答案!
【解决方案2】:

forEach 和slice 的问题是列表缩小但索引继续前进,因此元素被跳过。相反,我会推荐filter

nestedArray = [ { source : "a" , target : "b", table : "ab" }, 
{ source : "c" , target : "d", table : "cd" }, 
{ source : "a" , target : "d", table : "cd" }, 
{ source : "a" , target : "f", table : "cd" }];

const result = nestedArray.filter(o => o.source !=='a');

console.log(result);

如果需要 forEach 而不是 filter 创建新列表,请参阅 this answer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 2018-01-08
    • 2020-09-06
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    相关资源
    最近更新 更多