1

I have an array of results. I want to filter the results to an array whose categorys have at least one object with a cat_id of 1. How can I do that?

"results": [
  {
    "product_id": 1,
    "title": "booking",
    "draft": false,
    "publish": true,
    "category": [
      {
        "cat_id": 1,
        "cat_name": "web",
        "product": "booking"
      }
    ],
  },
  {
    "product_id": 2,
    "title": "reading",
    "draft": false,
    "publish": true,
    "category": [
      {
        "cat_id": 6,
        "cat_name": "android",
        "product": "asdasd"
      }
    ],
  },
  {
    "product_id": 3,
    "title": "reading",
    "draft": false,
    "publish": true,
    "category": [],
  },
]

My attempt:

for (let i = 0; i < data.results.length; i++) {
  this.webCatProducts = data.results[i].category.filter(d => d.cat_id == 1)
  console.log(this.webCatProducts)
}
1
  • yes it can be empty or have 3 objects that you can see above Commented May 28, 2018 at 5:18

2 Answers 2

3

Use .some inside the .filter to check to see if any of the category objects have a matchingcat_id:

const results=[{"product_id":1,"title":"booking","draft":!1,"publish":!0,"category":[{"cat_id":1,"cat_name":"web","product":"booking"}],},{"product_id":2,"title":"reading","draft":!1,"publish":!0,"category":[{"cat_id":6,"cat_name":"android","product":"asdasd"}],},{"product_id":3,"title":"reading","draft":!1,"publish":!0,"category":[],},];
const filtered = results.filter(
  ({ category }) => category.some(({ cat_id }) => cat_id === 1)
);
console.log(filtered);

Sign up to request clarification or add additional context in comments.

Comments

0

You should do filter on product level results: [] and predicate matched with expected category’s id with nested find some like this; .filter(product => product.category.some(cat => cat.cat_id === 1)

Make sure that category is always an array otherwise you have to check more.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.