简体   繁体   English

在 JavaScript 中的对象数组中过滤对象上的数组

[英]Filter on arrays on Objects inside array of Objects in JavaScript

I would like to get an array of the Main by category我想按类别获取 Main 的数组

[
  {
    "@id": "/api/main/7648",
    "@type": "Main",
    category: [{
      name: "laboriosam"
    }]
  },
  {
    "@id": "/api/main/7647",
    "@type": "Main",
    category: [{
        name: "foo"
      },
      {
        name: "bar"
      }
    ]
  }
]

So I try:所以我尝试:

console.log([...this.state.mains].filter(main => main.category.filter(category => category.name == "foo")))

But it returns me everything and I don't understand why?但它返回了我的一切,我不明白为什么?

Using Array.prototype.some , you can decide if the value is existed or not.使用Array.prototype.some ,您可以决定该值是否存在。

Using Array.filter function, it filters the true values only so it is needed to return boolean value on callback.使用Array.filter函数,它仅过滤true值,因此需要在回调时返回布尔值。

 const input = [{ "@id": "/api/main/7648", "@type": "Main", category: [{ name: "laboriosam" }] }, { "@id": "/api/main/7647", "@type": "Main", category: [{ name: "foo" }, { name: "bar" } ] } ]; console.log(input.filter(main => main.category.some(category => category.name == "foo")))

I find your question really hard to understand.我觉得你的问题真的很难理解。 If you want just the objects with @type = "Main" you can do如果你只想要@type = "Main" 的对象,你可以这样做

this.state.mains.filter(x => x["@type"] === "Main");

If you then want to filter those out who don't have a certain category you can add another filter like so:如果您想过滤掉那些没有特定类别的人,您可以添加另一个过滤器,如下所示:

this.state.mains
   .filter(x => x["@type"] === "Main")
   .filter(x => x.category.findIndex(c => c.name === "foo") !== -1);

Obviously in case of big array you also put both checks into one filter, but that might not be as readable.显然,在大数组的情况下,您还将两个检查都放入一个过滤器中,但这可能不那么可读。

Also note that [...this.state.mains].filter(...) is redundant, as .filter() already returns a new array.还要注意[...this.state.mains].filter(...)是多余的,因为.filter()已经返回一个新数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM