0

I have a list of products as an array of object, something like

[ {
   id: 1,
   price: 10,
   name: 'product',
   categories: [
                 {id: 1, name: 'category 1'} ]
   }, 
{
   id: 2,
   price: 10,
   name: 'product3',
   categories: [
                 {id: 1, name: 'category 1'},
                  {id: 2, name: 'category 2'},]
   }, 
... 
]

And so on.

I'm trying to filter the product based on the category id, which is the best (and most modern) approach?, also since I'm working with Node.js, can it be better to work on a "copy" of the data, so that I always keep the full dataset intact for other uses? (like another filtering, or filter remove)

1
  • 1
    theArray.filter(product => product.categories.find(category => category.id === desiredId)) Commented Dec 4, 2020 at 22:26

3 Answers 3

1

I'd use filter to apply a condition on each object. In that condition, I'd use some on the categories in order to find a product with at least one category that matches the condition:

const searchCategory = 1; // Just an exmaple
const result = products.filter(p => p.categories.some(c => c.id === searchCategory));
Sign up to request clarification or add additional context in comments.

Comments

1

I would use .filter(), and in the callback, I'd use .some() to check if any of the categories have the correct id. If you only need one, you can use .find() instead of .filter().

Since you're working with object references, you have to be careful since the objects in the filtered array point to the same objects as the original array. In other words, if you modify the first element of the filtered array, the original array will update.

As for your question of whether you need to keep the full dataset, the way you phrased it is too broad to properly answer. You obviously should keep all the data somewhere, but at which level you use a filtered array and which level the full array is up to your architectural decisions.

Comments

0

Use Array.filter()

const arr = [ {
   id: 1,
   price: 10,
   name: 'product',
   categories: [
                 {id: 1, name: 'category 1'} ]
   }, 
{
   id: 2,
   price: 10,
   name: 'product3',
   categories: [
                 {id: 1, name: 'category 1'},
                  {id: 2, name: 'category 2'},]
   }
]

arr.filter(_o => _o.categories.filter(_c => _c.id === 2).length) // Change the "2" to whatereve you like to match the category ID

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.