简体   繁体   中英

Filter on arrays on Objects inside array of Objects in JavaScript

I would like to get an array of the Main by category

[
  {
    "@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.

Using Array.filter function, it filters the true values only so it is needed to return boolean value on callback.

 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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