在Reactjs中从Spotify API中删除重复数据

问题描述 投票:0回答:1

所以我正在以 JSON 格式获取数据 Spotify API,但我收到的数据是重复的,我想删除重复的数据...
那么下面的函数是做什么的:它从 Spotify API 获取数据,正如你所看到的,我将获取的数据存储在 ```setAlbums()``` (这是一个 useState 对象 const 数组)中。
  const artistInfoHandler = (id) => {
    setLoading(true);
    setAlbums([]);
    fetch(`https://api.spotify.com/v1/artists/${id}/albums`, {
      headers: {
        Accept: "application/json",
        Authorization: `Bearer ${data.access_token}`,
        "Content-Type": "application/json",
      },
    })
      .then((response) => response.json())
      .then((response) => {
        console.log(response);
        for (let i = 0; i < response.items.length; i++) {
          setAlbums((old) => [
            ...old,
            {
              albumTitle: response.items[i].name,
              albumImage: response.items[i].images[0].url,
            },
          ]);
        }
      })
      .catch((error) => console.log(error));

    setLoading(false);
  };

这是输出:
0: {albumTitle: 'Certified Lover Boy', albumImage: 'xxxxxxxxxxxx'}
1: {albumTitle: 'Certified Lover Boy', albumImage: 'xxxxxxxxxxxxxxxxxx'}
2: {albumTitle: 'Dark Lane Demo Tapes', albumImage: 'xxxxxxxxxxxxxxxxxx'}
3: {albumTitle: 'Dark Lane Demo Tapes', albumImage: 'xxxxxxxxxxxx'}
4: {albumTitle: 'Care Package', albumImage: 'xxxxxxxxxxxx'}
5: {albumTitle: 'Care Package', albumImage: 'xxxxxxxxxxxx'}
6: {albumTitle: 'So Far Gone', albumImage: 'xxxxxxxxxxxx'}
7: {albumTitle: 'Scorpion', albumImage: 'xxxxxxxxxxxx'}
8: {albumTitle: 'Scorpion', albumImage: 'xxxxxxxxxxxx'}
9: {albumTitle: 'More Life', albumImage: 'xxxxxxxxxxxx'}
10: {albumTitle: 'More Life', albumImage: 'xxxxxxxxxxxx'}
11: {albumTitle: 'Views', albumImage: 'xxxxxxxxxxxx'}
12: {albumTitle: 'Views', albumImage: 'xxxxxxxxxxxx'}
13: {albumTitle: 'What A Time To Be Alive', albumImage: 'xxxxxxxxxxxx'}
14: {albumTitle: 'What A Time To Be Alive', albumImage: 'xxxxxxxxxxxx'}
15: {albumTitle: "If You're Reading This It's Too Late", albumImage: 'xxxxxxxxxxxx'}
16: {albumTitle: "If You're Reading This It's Too Late", albumImage: 'xxxxxxxxxxxx'}
17: {albumTitle: 'Nothing Was The Same (Deluxe)', albumImage: 'xxxxxxxxxxxx'}
18: {albumTitle: 'Nothing Was The Same (Deluxe)', albumImage: 'xxxxxxxxxxxx'}
19: {albumTitle: 'Nothing Was The Same', albumImage: 'xxxxxxxxxxxxxxxxxx'}




现在,当我不使用对象数组时,即当我将数据存储在不同的状态 const 中时,我可以通过以下方式删除重复项:

const newAlbums = [...new Set(albums)]
但是当我使用对象数组时我无法这样做。

javascript reactjs spotify
1个回答
0
投票

就你而言,我认为你应该这样做:

//removes duplicate names
var filteredItems = response.items.filter((v,i,a)=>a.findIndex(v2=>(v2.name===v.name)) === i);
//maps to a new object array
var newArray = filteredItems.map(x => ({
     albumTitle: x.name,
     albumImage: x.images[0].url,
}));
© www.soinside.com 2019 - 2024. All rights reserved.