下划线中的 where() 没有按预期工作

where() in underscore didn't work as expected

我在使用 _.where() 时遇到了一些问题。它没有按预期工作。 这是我的例子 JSON,

var result = [
  {
    image: {
      id: 158,
      ig_id: "968545232755317101_1532289565",
      status: "hide",
    },
    id: 1,
    month: 4,
    year: 2015
  },
  {
    image: {
      id: 152,
      ig_id: "968547282620733844_1532289565",
      status: "approve",
    },
    id: 2,
    month: 4,
    year: 2015
  },
]

我想在 image.status = 'hide' 处获取集合。我喜欢这个,

console.log(_.where(result.image, { status : 'hide'})); // This return []
console.log(_.where(result, { image.status : 'hide'})); // This will error
console.log(_.where(result, { 'image.status' : 'hide'})); // This return []

我不知道如何以正确的方式做到这一点。我真的需要帮助。

谢谢。

你可以像这样使用 vanilla JS 来做到这一点:

console.log(result.filter(function (value) { 
    return value.image.status === 'hide'; 
}));

我不相信 Underscore.js 支持 where() 中的深度比较,但如果你使用 lodash,这有效:

console.log(_.where(result, { image: {status : 'hide'}}));