【问题标题】:filter array object with array value用数组值过滤数组对象
【发布时间】:2020-12-11 05:31:26
【问题描述】:

我正在尝试用数组值过滤一个数组对象,这里是代码:

const array1 = [{
            "packaging": "Box",
            "price": "100"
        }, {
            "packaging": "Pcs",
            "price": "15",
        }, {
            "packaging": "Item",
            "price": "2",
        }];

const b = ['Pcs','Item']
const found = array1.filter(el => {
    for(i = 0; i < b.length; i++) {
      return el.packaging !== b[i];
    }
});

console.log(found);

我的预期输出是数组,其中 b 中不存在对象 [{包装:“盒”,价格:“100”}]

【问题讨论】:

  • 您的嵌套 for 循环是不必要的,.filter 已经在元素上循环。按照下面的答案做,然后立即返回所需的条件(使用.includes

标签: javascript ecmascript-6 ecmascript-5


【解决方案1】:

改用.includes 检查:

const array1 = [{
            "packaging": "Box",
            "price": "100"
        }, {
            "packaging": "Pcs",
            "price": "15",
        }, {
            "packaging": "Item",
            "price": "2",
        }];

const b = ['Pcs','Item']
const found = array1.filter(el => !b.includes(el.packaging));
console.log(found);

【讨论】:

  • 使用includes 代替b.indexOf(item) == -1 很快。 :) 但是,就性能而言,您是否总是建议在老式方式之前使用包含?还是两者相等?
  • .includes 可能会更快一些,因为它不必查看索引,只需返回一个布尔值 - 但在现实世界中更重要的是可读性,95% 的时间,.includes 胜出。
【解决方案2】:

您应该执行以下操作,

const array1 = [{
            "packaging": "Box",
            "price": "100"
        }, {
            "packaging": "Pcs",
            "price": "15",
        }, {
            "packaging": "Item",
            "price": "2",
        }];

const b = ['Pcs','Item']
const found = array1.filter(el => {
    return b.findIndex(item => item === el.packaging) <= -1;
});

console.log(found);

【讨论】:

    【解决方案3】:

    这能解决您的问题吗?

    const arr1 = [
      {"packaging": "Box", "price": "100"}, 
      {"packaging": "Pcs", "price": "15"}, 
      {"packaging": "Item", "price": "2"}
    ];
    
    const arr2 = ['Pcs','Item'];
    const found = arr1.filter(item => {
      return arr2.indexOf(item.packaging) === -1;
    });
    
    console.log(found);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-17
      • 1970-01-01
      • 2022-11-27
      • 2023-04-10
      • 2021-11-10
      • 2021-08-27
      相关资源
      最近更新 更多