无法将对象过滤出数组

时间:2019-08-21 23:02:32

标签: javascript arrays object filter

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

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' } ]

我在这里想念什么?

4 个答案:

答案 0 :(得分:3)

这将起作用:

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

console.log(bar);

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

答案 1 :(得分:2)

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

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 :(得分:0)

使用较短的符号

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

console.log(bar);

答案 3 :(得分:-1)

您需要打开对象进行比较。这样的事情会起作用

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