OR.(||)运算符在angular.forEach中不起作用吗? [英] OR (||) operator in angular.forEach not working?

查看:48
本文介绍了OR.(||)运算符在angular.forEach中不起作用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下json数组,并且需要在某些条件下删除其中一些:

I have the following json array, and need to remove some of them by certain conditions:

var data = [
             {data1: "aaa", data2: "bbb", data3: "ccc"},  // First
             {data1: "ddd", data2: "eee", data3: "fff"},  // Second
             {data1: "ggg", data2: "hhh", data3: "iii"},  // Third
             {data1: "jjj", data2: "eee", data3: "lll"}   // Fourth
           ];
angular.forEach(data, (item, i) => {
  if (item.data2 == 'eee' || item.data3 == 'iii') {
    data.splice(i, 1);
  }
});
console.log(data);

在上述情况下,我需要从数据数组中删除第二个(data2具有"eee"),第三个(data3具有"iii")和第四个(data2是"eee")对象.但是,第三个对象没有被拼接,而是保留在数据数组中.

In the above case, I need to remove second (data2 has "eee"), third (data3 has "iii"), and fourth (data2 is "eee") object from the data array. However, the third object is not spliced and remains in data array.

我可以通过这种方式使用OR(||)运算符吗?如果没有,使用多个条件从数组中删除元素的正确方法是什么?

Could I use OR (||) operator in this manner? If not, what is the proper way to remove elements from array using multiple conditions?

这个问题我已经花了好几个小时的时间,但是也许我错过了一些东西.

I've been scratching my head around for hours with this problem, but perhaps I'm missing something.

推荐答案

请改用过滤器,使用拼接时,您要更改要迭代的数组,该数组为否:

Use filter instead, When using splice you change the array you want to iterate on which is a no no:

var data = [
             {data1: "aaa", data2: "bbb", data3: "ccc"},  // First
             {data1: "ddd", data2: "eee", data3: "fff"},  // Second
             {data1: "ggg", data2: "hhh", data3: "iii"},  // Third
             {data1: "jjj", data2: "eee", data3: "lll"}   // Fourth
           ];
var filtered = data.filter(function (element) {
    return element.data2 !== 'eee' && element.data3 !== 'iii';
});
console.log(filtered);

这篇关于OR.(||)运算符在angular.forEach中不起作用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆