0

var object1 = {
  lol_gif: [22390036, 15154597, 13491369],
  silly_gif: [19048808, 19048861]
}

var ids = Object.values(object1).toString();//will return 22390036,15154597,13491369,19048808,19048861
httpGetAsync('https://g.tenor.com/v1/gifs?ids=' + ids + '&key=LIVDSRZULELA&media_filter=tinygif');


function httpGetAsync(theUrl) {
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
      var response = JSON.parse(xmlHttp.responseText);
      var gifs = response.results;
      var object2 = {};
      for (var g in gifs) {
        var id = gifs[g].id;
        object2[id] = gifs[g].media[0].tinygif.url;
      }
      console.log(object2);
      //will return an object with the ID as the keys and gif url as the values
    }
  }
  xmlHttp.open("GET", theUrl, true);
  xmlHttp.send();
  return;
}
I am trying to categorize each gif by replacing object1 values with data from tenor json but failed many times. thanks for your help!

desired output:

var object1 = {
  lol_gif: ["https://media.tenor.com/images/4ad4bc701f2744ddc5220f6d3688e899/tenor.gif",
            "https://media.tenor.com/images/c9b8564d6acbbba994b5413479d0fc2b/tenor.gif",
            "https://media.tenor.com/images/7c27bea2fb5ea0f7600af7e9ad8d0c4a/tenor.gif"],
  silly_gif: ["https://media.tenor.com/images/59669ec95913ef1df85fee2cda08aece/tenor.gif",
              "https://media.tenor.com/images/59669ec95913ef1df85fee2cda08aece/tenor.gif"]
}
4
  • 1
    When you combine all the values into a single string, you no longer distinguish between lol_gif and silly_gif. Commented May 3, 2022 at 21:16
  • 1
    What does the response JSON look like? Commented May 3, 2022 at 21:16
  • pls run code snippet to see the response. Commented May 3, 2022 at 21:18
  • 1
    it can be distinguish by matching keys of object2/response with object1 values but cant seem to find a good starting point... Commented May 3, 2022 at 21:23

3 Answers 3

2

Something like this would give you an object in the same shape as your original:

var object1 = {
  lol_gif: [22390036, 15154597, 13491369],
  silly_gif: [19048808, 19048861]
}

var ids = Object.values(object1).toString();//will return 22390036,15154597,13491369,19048808,19048861
httpGetAsync('https://g.tenor.com/v1/gifs?ids=' + ids + '&key=LIVDSRZULELA&media_filter=tinygif');


function httpGetAsync(theUrl) {
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
      var response = JSON.parse(xmlHttp.responseText);
      var gifs = response.results;

      var object2 = {};

      Object.entries(object1).forEach(([key, gifIds]) => {
        const newGifList = gifIds.map((gifId) => {
          const gif = gifs.find((gifResult) => gifResult.id === gifId.toString());
          return gif.media[0].tinygif.url;
        });

        object2[key] = newGifList;
      });

      console.log(object2);
      //will return an object with the ID as the keys and gif url as the values
    }
  }
  xmlHttp.open("GET", theUrl, true);
  xmlHttp.send();
  return;
}

Side note, its generally not a great idea to include API keys in StackOverflow questions.

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

3 Comments

thanks. Im actually using their default api :)
Ah ok, that should be fine then. Its always just a little scary to see API keys in plain text haha
@ChrisSandvik true
1

I haven't really taken a deep dive into the type of responses this API provides back, but my surface-level conclusion is that if you want to maintain the exact structure and order of the data, you'll have to go with this solution:

const object = {
    lolGifs: [22390036, 15154597, 13491369],
    sillyGifs: [19048808, 19048861],
};

const getGifs = async (obj) => {
    const map = {};

    for (const [key, arr] of Object.entries(obj)) {
        map[key] = [];

        for (const id of arr) {
            const res = await fetch(`https://g.tenor.com/v1/gifs?ids=${id}&key=LIVDSRZULELA&media_filter=tinygif`);
            const { results } = await res.json();

            const gifUrl = results[0]?.media[0]?.tinygif?.url;
            map[key].push(gifUrl);
        }
    }

    return map;
};

(async () => {
    const data = await getGifs(object);
    console.log(data);
})();

5 Comments

thanks for the answer, ill take a look.
Splitting each ID into its own request won't scale very well if you need to make a large number of requests, especially when doing it all in one request is an option.
@ChrisSandvik I agree, and I would never implement this code. Just he wants the desired output to be a certain way, and the API doesn't provide the same identifiers he is using.
correct me if im wrong, this is making multiple api request right?
@88willr yes. it is.
0

You just need to make some simple change where you search for the ids to put it to the keyname as following:

var object1 = {
  lol_gif: [22390036, 15154597, 13491369],
  silly_gif: [19048808, 19048861]
}

var ids = Object.values(object1).toString();//will return 22390036,15154597,13491369,19048808,19048861
httpGetAsync('https://g.tenor.com/v1/gifs?ids=' + ids + '&key=LIVDSRZULELA&media_filter=tinygif');


function httpGetAsync(theUrl) {
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
      var response = JSON.parse(xmlHttp.responseText);
      var gifs = response.results;
      var object2 = {"lol_gif":[],"silly_gif":[]};
      for (var g in gifs) {
        var id = gifs[g].id;
        if(object1["lol_gif"].indexOf(parseInt(id))!=-1) {
          object2["lol_gif"].push(gifs[g].media[0].tinygif.url);
        }
        else if(object1["silly_gif"].indexOf(parseInt(id))!=-1){
        object2["silly_gif"].push(gifs[g].media[0].tinygif.url);
        }
      }
      console.log(object2);
      //will return an object with the ID as the keys and gif url as the values
    }
  }
  xmlHttp.open("GET", theUrl, true);
  xmlHttp.send();
  return;
}

2 Comments

thanks for your answer but Im not sure if it's a good idea to keep rewriting the condition as I add more categories...
@88willr, just wanted to point out where you were wrong using your code. you can clean it up, but without condition, you won't be able to separate the lol_gif and silly_gif

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.