1

I have DB (use json-server) like this:

DB = {
  products: [
    {id: 0, name: 'aaa', price: 10},
    {id: 1, name: 'bbb', price: 20},
    {id: 2, name: 'ccc', price: 50},
    {id: 3, name: 'ddd', price: 1}
  ]
};

And array of ids:

cartItemsIds: [0, 3];

How can I get array of objects from DB with ids from cartItemsIds ?

2
  • Does this answer your question? How to filter an array from all elements of another array Commented May 2, 2020 at 9:01
  • Not exactly. This method should be work, but I know that json-server has inline filter feature. So there's no need to load all db.products, but filter them on server side. Commented May 2, 2020 at 10:09

2 Answers 2

1

Solved. If anyone needs:

`products?id=${cartItemsIds.join('&id=')}`
Sign up to request clarification or add additional context in comments.

Comments

0

You can loop over your products from db like so:

for(const product of DB.products) {    
  if(cartItemsIds.includes(product.id)) {
   console.log(product);
  }
}

4 Comments

I don't want to get all DB.products and then filter them, but I want to filter them on server side at first and then get filtered array of objects.
my bad. I took a fast look to the docs. have you tried doing something like /products/id_like=${carItemsIds}?
or /products/id_like=${carItemsIds.join(',')}?
It needs to right request, request that you propose doesn't work even if carItemsIds contains only one element. But thanks for answer:)

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.