简体   繁体   中英

How can I fetch objects from an array from an array which match an array of id's?

How can I fetch objects from an array from an array which match an array of id's? Is this possible? I'd ideally like to grab only the ones that I need, rather than fetching objects that I don't need and then filtering them as this seems not very performant.

const objects = [
 {
  id: "1", 
  name : "one",
 },
 {
  id: "1", 
  name : "two"
 },
 {
  id: "3", 
  name : "three",
 },
 {
  id: "4", 
  name : "four"
 },
 {
  id: "5", 
  name : "five"
 }
]
const ids = ['1', '3', '5'];
let myFilteredObjects = await fetch('./objects');
// myObjects should return and an array of objects with 1, 3, 5

If I get it right you want to send only the list of ids and receive only the matching objects.

search for "MDN fetch", "MDN array filter", "MDN array find"

With fetch you actually do a combination of request/response to/from a backend. So basically you want to send the "ids" of interest to an url, let the backend do the filtering and get the objects that match in the response.

backend (if implemented with javascript) could return:

objects.filter(obj => ids.includes(obj.id))

or:

objects.filter(x => x.id === ids.find(y => y === x.id))

Note: the name "id" is probably not the best choice as it usually is used for a unique relation, meaning if you input an id somewhere it should only return one value (search "wiki ID")

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