-4

Here's my code:

{ 
"badge_sets":{
   "1979-revolution_1":{
      "versions":{
         "1":{
            "image_url":"https://static-cdn.jtvnw.net/badges/v1/7833bb6e-d20d-48ff-a58d-67fe827a4f84/1",
         }
      }
   },
   "60-seconds_1":{
      "versions":{
         "1":{
            "image_url":"https://static-cdn.jtvnw.net/badges/v1/1e7252f9-7e80-4d3d-ae42-319f030cca99/1",
         }
      }
   }
}}

Im trying to get something like that using javascript but currently i have no idea how to do it, Can someone help?

1979-revolution_1;https://static-cdn.jtvnw.net/badges/v1/7833bb6e-d20d-48ff-a58d-67fe827a4f84/1
60-seconds_1;https://static-cdn.jtvnw.net/badges/v1/1e7252f9-7e80-4d3d-ae42-319f030cca99/1
3xanax
  • 21
  • 4

1 Answers1

4

You can use ES6's Object.entries() so access the key and value of the nested badge_sets object. Remember that Object.entries() return a [key, value] tuple, so we can use argument destructuring to assign those variables.

The image URL can then be accessed using a combination of dot and bracket notation as such. Then, it is all about using ES6 template literal to put all the parts together to get the format you want.

Object.entries(data.badge_sets).map(([key, value]) => {
  return `${key}:${value.versions['1'].image_url}`;
});

Note that this solution will return an array of formatted strings.

You can even take advantage of implicit returns from ES6's arrow function to have a one-liner, at the expense of readability (but looks nice!)

const formattedData = Object.entries(data.badge_sets).map(([key, value]) => `${key}:${value.versions['1'].image_url}`);

See proof-of-concept example:

const data = {
  "badge_sets": {
    "1979-revolution_1": {
      "versions": {
        "1": {
          "image_url": "https://static-cdn.jtvnw.net/badges/v1/7833bb6e-d20d-48ff-a58d-67fe827a4f84/1",
        }
      }
    },
    "60-seconds_1": {
      "versions": {
        "1": {
          "image_url": "https://static-cdn.jtvnw.net/badges/v1/1e7252f9-7e80-4d3d-ae42-319f030cca99/1",
        }
      }
    }
  }
};

const formattedData = Object.entries(data.badge_sets).map(([key, value]) => `${key}:${value.versions['1'].image_url}`);
console.log(formattedData);
Terry
  • 63,248
  • 15
  • 96
  • 118