【问题标题】:Can't filter object out of array无法从数组中过滤对象
【发布时间】:2023-04-08 17:42:02
【问题描述】:

我正在尝试使用以下方法从数组中过滤出一个对象:

foo = [{foo: 'bar'}, {baz: 'bar'}];
bar = foo.filter(function(i) {
  return i !== {foo: 'bar'}
})

当我之后登录bar 时,我得到了完整的数组。

以下代码

foo.filter(function(i) {
  console.log(i === {foo: 'bar'});
  console.log(i);
  console.log({foo: 'bar'});
  return i !== {foo: 'bar'}
})

返回:

false
{ foo: 'bar' }
{ foo: 'bar' }
false
{ baz: 'bar' }
{ foo: 'bar' }
[ { foo: 'bar' }, { baz: 'bar' } ]

我在这里错过了什么??

【问题讨论】:

    标签: javascript arrays object filter


    【解决方案1】:

    几乎,i 是实际对象。因此,您只需要将 i.foo 与字符串 bar 进行比较即可。与i === {} 之类的对象进行比较永远不会奏效。您需要比较 i 和您的 object 中的所有属性。如果您想要那种东西,那里有很多深度比较助手/示例。

    Array.filter

    /*
    foo = [{foo: 'bar'}, {baz: 'bar'}];
    bar = foo.filter(function(i) {
      return i !== {foo: 'bar'} // <-- You can't compare i to an object like this
    })
    */
    
    /**
    * Array.filter will provide you with each object in your array.
    * `i` is already the object in which you're trying to compare
    * so you just need to access the property you want to compare (foo)
    * and then compare if to the string 'bar'. i !== { prop: 'val' }
    * will not give you accurate results
    */
    foo = [{foo: 'bar'}, {baz: 'bar'}];
    bar = foo.filter(function(i) {
      return i.foo !== 'bar'; // i is already the object. Access the property and then compare
    });
    console.log(bar);

    如果您认为需要进行深度比较,请查看以下内容:Object comparison in JavaScript

    【讨论】:

      【解决方案2】:

      使用更短的符号

      let foo = [{foo: 'bar'}, {baz: 'bar'}];
      let bar = foo.filter(i => i.foo !== 'bar');
      
      console.log(bar);

      【讨论】:

        【解决方案3】:

        您需要打开对象进行比较。像这样的东西会起作用

        foo = [{foo: 'bar'}, {baz: 'bar'}];
        bar = foo.filter(function(i) {
           const [key, value] = Object.entries(i)[0];
           return key === 'foo' && value === 'bar'
        })
        

        【讨论】:

        • (没有投票给你)。我喜欢你在比较财产和价值方面的收获。但我认为 op 严格在属性 foo 等于 bar 的对象之后
        【解决方案4】:

        这可行:

        const foo = [{foo: 'bar'}, {baz: 'bar'}];
        const bar = foo.filter(function(i) {
          return i.foo !== 'bar'
        });
        
        console.log(bar);

        您应该比较属性 'foo' 本身,而不是比较两个对象

        【讨论】:

        • 我想这是最好的方法。
        猜你喜欢
        • 1970-01-01
        • 2021-10-24
        • 2021-07-05
        • 2022-08-15
        • 1970-01-01
        • 1970-01-01
        • 2020-02-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多