Home > Software engineering >  Combining the response.JSON data from two separate Spotify API Queries?
Combining the response.JSON data from two separate Spotify API Queries?

Time:12-16

I'm very new to Javascript/web dev and attempting to pull data from the Spotify API to use in a website. Performing two separate queries to pull the data I need, and trying to combine the two response.json objects using

const data = Object.assign(source, target).

However, when I do so, only the second object (target) gets assigned to data and shows up in my web app. I believe the first entry in data2 is identical to the last entry in data1 (key, value), not sure if this might be causing the issue, but from what I've read, data2 should just override that entry in data1. Considering keeping these response objects separate and just trying to combine the data in a further step (combining two maps), but not quite sure the correct syntax to use for this process as I keep getting errors there too. Any help would would be greatly appreciated! Code below.

const fetchTopSongs = async (duration) => {
        const response1 = await window.fetch('https://api.spotify.com/v1/me/top/tracks?'  
            querystring.stringify({
              limit: 50,
              offset: 0,
              time_range: duration,
            }), {
            method: 'GET',
            headers: {
                Authorization: 'Bearer '   accessToken,
            },
        });
        const data1 = await response1.json()
        const response2 = await window.fetch('https://api.spotify.com/v1/me/top/tracks?'  
            querystring.stringify({
              limit: 50,
              offset: 49, 
              time_range: duration,
            }), {
            method: 'GET',
            headers: {
                Authorization: 'Bearer '   accessToken,
            },
        });
        const data2 = await response2.json()
        const data = Object.assign(data1,data2)
        // const map1 = data1.items.map(song => song.name)
        // const map2 = data2.items.map(song => song.name)
        // const map = new Map([...map1,...map2])
        // setTopSongs(map)
        setTopSongs(data.items.map(song => song.name))
    }

CodePudding user response:

It will be good to have an example of the response, but based on the search api

It looks like the response is something like:

{
  "tracks": {
    href: foo,
    items: [],
    total: bar
  }
}

Said that, I think you need to merge the items array

const result = [...data1.items, ...data2.items]

CodePudding user response:

what about creating a customize function that accept 3 params and combine all of data inside it and then return result .

here u debug the result to insure that is already here with log(response11);but when since using await it will result in undefiend or error it's not there and it will be at some point at some point so insted consider doing this , since it's A Promise that resolves to a JavaScript object here

 const data1 = await response1.json().then(()=>{
    console.log(data1)
    }).catch(e => console.log(e))

      //also here do it with the same way
        const data2 = await response2.json().then(()=> {

  const data = Object.assign(data1,data2)
  return   setTopSongs(data.items.map(song => song.name))

}).catch(e => console.log(e))
    }

here u can do it with multiable way u can see this high rate answer to combine multiable objects in one u can do it with

const data = Object.assign(data1,data2)

u can use

const allRules = Object.assign({}, data1,data2 , etc);

(see MDN JavaScript Reference)

or with : ECMAScript 2018 Standard Method

object spread syntax notice that allRules is now the union of data1 and data2. Properties in data2 will overwrite those in data1.

let allRules = {...data1, ...data2 };

or as i said befor u may need in case like so to use customize function to merge those json object this also work with when you need to merge two objects without overwriting overlapping object keys

const allRules  = (...objects) => {
  return objects.reduce((prev, next) => {
    Object.keys(prev).forEach(key => {
      next[key] = { ...next[key], ...prev[key] }
    })
    return next
  })
}

more example needed for this in here SOF question and answer

finally could u provide more info about wich error is occured when u trying to do so , and also response log to have a good vision about what exactly u need

  • Related