0

I want to get things with collectionId that match those in the list. In other words, I want to get the desired result. How can I do it?? please help me....

const music_list = {
  "resultCount": 50,
  "results": [{
      "collectionId": 123,
      "ArtistId": "BLACKPINK"
    },
    {
      "collectionId": 456,
      "ArtistId": "BTS"
    },
    {
      "collectionId": 789,
      "ArtistId": "CARDIBI"
    }
  ]
}
const list = [123, 142, 118];

In this situation, Desired result = [{"collectionId":123, "ArtistId": "BLACKPINK"}]

1
  • filter and includes Commented Apr 27, 2022 at 17:26

1 Answer 1

2

You can map the list to the relevant objects - for each ID, you will try to find the corresponding object in the results array. At the end, you can filter out the missing elements.

const result = list
  .map(id => music_list.results.find(item => item.collectionId === id))
  .filter(item => item)

How it works: music_list.results.find(item => item.collectionId === 123) would return the item in music_list.results that has collectionId: 123 (or undefined if no such item exists). Furthermore, list.map(id => ...something...) would apply the ...something... to each id in the list and return a new array with the results. So here we map the IDs to the matching objects in your results array. At the end, we use filter to remove elements that are falsy (undefined is falsy), i.e. remove the missing elements from the result (without that, it would return something like [{ ... }, undefined, undefined]).

You can see it in action here:

const music_list = {
  "resultCount": 50,
  "results": [
    {
      "collectionId": 123,
      "ArtistId": "BLACKPINK"
    },
    {
      "collectionId": 456,
      "ArtistId": "BTS"
    },
    {
    "collectionId": 789,
    "ArtistId": "CARDIBI"
    }
  ]
}

const list = [123, 142, 118];

const result = list
  .map(id => music_list.results.find(item => item.collectionId === id))
  .filter(item => item);

console.log(result);

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

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.