Retrieving information from a JSON file using JavaScript

My code snippet looks like this:

{ 
"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",
         }
      }
   }
}}

I am attempting to achieve a similar result using JavaScript, however, I am struggling with the implementation. Can anyone provide assistance?

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

Answer №1

To access the key and value of the nested badge_sets object, you can utilize ES6's Object.entries(). Remember that Object.entries() returns a [key, value] tuple, allowing for argument destructuring to assign those variables.

The image URL can be retrieved using a mix of dot and bracket notation. Then, with the use of ES6 template literals, you can piece together all the components to achieve the desired format.

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

It's important to note that this approach will yield an array of formatted strings.

For a more concise one-liner solution, you can take advantage of implicit returns from ES6's arrow functions. This results in a more succinct code, albeit potentially sacrificing readability for brevity.

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

Check out the proof-of-concept example below:

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);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the built-in modules in node.js that handle System calls?

Can you list the built-in modules in Node.js that handle system calls, such as child_process? I'm interested in learning about all the methods within these modules. Thank you! ...

Creating an Array of Nested Sibling Objects Using Groovy's JsonBuilder

I am attempting to create a JSON array with multiple nested objects. Desired Output: [ { "User": { "Name": "Foo", "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="85f1e0f6f1c5e0fde4 ...

The absence of the 'Access-Control-Allow-Origin' header is reported even though it is actually present

I have been attempting to send a POST request from one website to my own site. Despite allowing CORS access explicitly, every time I try to make the actual POST request, I am faced with the No 'Access-Control-Allow-Origin' header is present on th ...

A pair of buttons each displaying a unique div block

I am facing an issue with my jQuery script. I want to be able to click on one of the previewed text associated with a button and then have the other one close automatically. The desired effect is for the text to slide down using slideDown() and disappear ...

Limit the Jquery selection specifically to elements on the modal page

Recently I encountered an issue with a webpage that opens a modal form. The problem arises when the validation function, written in JQuery, checks all fields on both the modal and the page beneath it. //validate function function validateFields() { v ...

Performing date comparison in JavaScript with varying date formats

My system includes a table that retrieves dates from an FTP location. On the user interface page, there is a form that gathers all details related to a specific FTP date. However, I am facing difficulties in comparing the FTP dates with those specified in ...

constructing Ruby on Rails Jbuilder JSON attributes with dynamic variable names

I am working on creating JSON output in Rails using jbuilder. My current code looks like this: json.links do | i | i.array!( @links ) do | j, link | j.source link['source'] j.target link['target'] j.stats do | s ...

Selecting the optimal data structure: weighing the benefits of using boolean check versus array .include (balancing performance and redundancy

My objects can have one or more properties assigned, with a total of 5 different properties in my case. To illustrate this, let's use a simple movie example where each movie can be assigned from 5 different genres. I have come up with two methods to ...

Guidance that utilizes the scope of a specific instance

I have successfully created a d3.js directive, but I am facing an issue when resizing the window. The values of my first directive seem to be taking on the values of my second directive. How can I separate the two in order to resize them correctly? (both ...

What is the best way to retrieve all SVG objects within a specific area in an Angular application?

I am currently developing an SVG drawing application and have implemented a tool that enables users to select all shapes within a rectangular area. However, I am facing the challenge of detecting the SVG shapes located underneath the selected rectangle. ...

CSS photo display with magnification feature

I currently have a functioning inner-zoomable image set up with the code provided. I am interested in converting this setup into an image gallery with zoom capabilities for the selected image element, but I'm unsure where to start. My objective is to ...

The Arabic content in the Json request is failing to be submitted

Encountering a problem when trying to post Arabic text in a Json Request field. The error message states: "The Request was Aborted; The Request was cancelled." I have attempted various encoding methods such as UTF8, ASCII, HTMLEncode, JavaScritpEncode, and ...

How about generating a promise that serves no real purpose and simply resolves?

Managing promises in Node.js can be a bit tricky, especially when dealing with different scenarios. One common use case is catching the last promise result and formatting it accordingly. req.resolve = (promise) => { return promise.then(() => { ...

Encountering a syntax error with the spread operator while attempting to deploy on Heroku

I'm encountering an error when attempting to deploy my app on Heroku: remote: SyntaxError: src/resolvers/Mutation.js: Unexpected token (21:16) remote: 19 | const user = await prisma.mutation.createUser({ remote: 20 | data: { r ...

Exploring the extracted data from a JSON file in text format

When making a JSON request to a server, I require access to a time-stamp that will adjust dynamically based on another time variable. Using the requests module, I am sending a post request with the JSON as a .txt file. Here is my JSON data. My goal is to ...

Why does Res.send return an empty object when console.log indicates it is not empty?

I am currently facing a challenge while using the Google Sheets API with Express, as I have limited experience with JavaScript. My goal is to pass a JSON object from Express to React, but for some reason, when I send the object, it appears empty on the fro ...

Leveraging Vue.js's computed properties to access and manipulate elements within an

I have a simple template that displays text from a wysiwyg editor using two-way data binding, as shown below: <template> <div> <quill-editor v-model="debounceText" :options="editorOptionProTemplate" > </qu ...

Error: Unable to assign value 'auto' to property of null object

Whenever I attempt to update my MongoDB using AngularJS on the front end and Node.js on the backend, I encounter a `TypeError: Cannot set property 'auto' of null error. Here is the code snippet that resulted in this issue: AngularJS Code: scope ...

Issue encountered in React 18: The value on the left side of an assignment statement must be a variable or a property that can be accessed

After upgrading my React version from 17 to 18, I encountered an error with this code: data?.area?.width=['111','220']. The error message states "The left-hand side of an assignment expression must be a variable or a property access." W ...

The console.log for a GET request in Express Router is displaying undefined parameters

After searching extensively on SO for a question similar to mine, I have come to the realization that my issue should be quite straightforward. The closest thread I discovered was this link. My current focus is on learning Node.JS, and I am in the process ...