Issue encountered in JavaScript - Struggling to display an element due to identical key names

I've been working on extracting data from a JSON response, but I'm running into an issue where I can't retrieve all the necessary values.

Below is the structure of the JSON response:

{
  "status": "success",
  "reservations": [
    {
      "id": "38177",
      "subject": "subjectID",
      "modifiedDate": "2017-05-16T12:46:17",
      "startDate": "2017-05-30T08:00:00",
      "endDate": "2017-05-30T22:00:00",
      "resources": [
        {
          "id": "124",
          "type": "room",
          "code": "F407",
          "parent": {
            "id": "4",
            "type": "building",
            "code": "buildingF",
            "name": "buildingName"
          },
          "name": " F407 (atk 34)"
        }
      ],
      "description": ""
    },
    { 
      // More reservation objects with similar structure
    }
  ]
}

The task at hand involves extracting the room code and name for each subject as shown below:

"code": "F407"
"name": "F407 (atk 34)"

"code": "F411"
"name": "F411 (atk 34)"

"code": "F211"
"name": "F211 (room 50)"

"code": "F312"
"name": "F312 (room 48)"

I've attempted to achieve this using my own code, however, it seems to skip one of the room names inexplicably. My approach involves iterating through the JSON response with for loops and retrieving the code and name within resources which are then added to an array:

var rooms = [];

for (var i = 0; i < json.reservations.length; i++) {
    if (json.reservations[i].resources != null) {
        for (var j = 0; j < json.reservations[i].resources.length; j++) {
            var reservation = json.reservations[i];
            var resource = json.reservations[i].resources[j];

            if (resource.type === "room") {
                if (rooms.indexOf("code")) {
                    rooms.push(resource.code + resource.name);
                }
            }
        }
    }
}

document.getElementById("pageOne").innerHTML = rooms.join("<br/>");

Upon execution, the output displays missing room names, specifically "name": "F411 (atk 34)".

Any insights on why this inconsistency might be occurring?

Answer №1

Have you found what you were looking for?

var data = {
  "status": "success",
  "reservations": [
    {
      "id": "38177",
      "subject": "subjectID",
      "modifiedDate": "2017-05-16T12:46:17",
      "startDate": "2017-05-30T08:00:00",
      "endDate": "2017-05-30T22:00:00",
      "resources": [
        {
          "id": "124",
          "type": "room",
          "code": "F407",
          "parent": {
            "id": "4",
            "type": "building",
            "code": "buildingF",
            "name": "buildingName"
          },
          "name": " F407 (atk 34)"
        }
      ],
      "description": ""
    },
    {
      "id": "38404",
      "subject": "subjectID",
      "modifiedDate": "2017-05-16T12:49:25",
      "startDate": "2017-05-30T08:00:00",
      "endDate": "2017-05-30T22:00:00",
      "resources": [
        {
          "id": "128",
          "type": "room",
          "code": "F411",
          "parent": {
            "id": "4",
            "type": "building",
            "code": "buildingF",
            "name": "buildingName"
          },
          "name": " F411 (atk 34)"
        }
      ],
      "description": ""
    },
    {
      "id": "38842",
      "subject": "subjectID",
      "modifiedDate": "2017-05-30T06:03:13",
      "startDate": "2017-05-30T08:00:00",
      "endDate": "2017-05-30T22:00:00",
      "resources": [
        {
          "id": "107",
          "type": "room",
          "code": "F211",
          "parent": {
            "id": "4",
            "type": "building",
            "code": "buildingF",
            "name": "buildingName"
          },
          "name": " F211 (room 50)"
        }
      ],
      "description": ""
    },
{
      "id": "40186",
      "subject": "subjectID",
      "modifiedDate": "2017-05-26T08:45:50",
      "startDate": "2017-05-30T09:00:00",
      "endDate": "2017-05-30T14:00:00",
      "resources": [
        {
          "id": "118",
          "type": "room",
          "code": "F312",
          "parent": {
            "id": "4",
            "type": "building",
            "code": "buildingF",
            "name": "buildingName"
          },
          "name": " F312 (room 48)"
        }
      ],
      "description": ""
    },
  ]
};


var roomsList = '';

for (var x = 0; x < data.reservations.length; x++) {
    if (data.reservations[x].resources != null) {
        
  for(var y=0; y<data.reservations[x].resources.length; y++){      roomsList +=data.reservations[x].resources[y].code +" " + data.reservations[x].resources[y].name+"</br>";
     }  
    }
}
document.getElementById("pageOne").innerHTML = roomsList;
<div id="pageOne"></div>

Answer №2

Utilize the powerful Array.prototype.map() method

The map() function generates a new array by executing a specified function on each element within the original array.

var res = data.reservations.map(function(_data) {
  return {
    code: _data.resources[0].id,
    name: _data.resources[0].name
  }
});

console.log(res);

SNIPPET

var data = {
  "status": "success",
  "reservations": [{
      "id": "38177",
      "subject": "subjectID",
      "modifiedDate": "2017-05-16T12:46:17",
      "startDate": "2017-05-30T08:00:00",
      "endDate": "2017-05-30T22:00:00",
      "resources": [{
        "id": "124",
        "type": "room",
        "code": "F407",
        "parent": {
          "id": "4",
          "type": "building",
          "code": "buildingF",
          "name": "buildingName"
        },
        "name": " F407 (atk 34)"
      }],
      "description": ""
    },
    {
      "id": "38404",
      "subject": "subjectID",
      "modifiedDate": "2017-05-16T12:49:25",
...
          "name": " F312 (room 48)"
      }],
      "description": ""
    },
  ]
};


var res = data.reservations.map(function(_data) {
  return {
    code: _data.resources[0].id,
    name: _data.resources[0].name
  }
});

console.log(res);

Answer №3

   myObject.reservations.forEach(function(reservation){reservation.rooms.
    forEach(function(room){console.log({"room_code":room.code,"room_name":room.name})})})

Answer №4

After running your code, everything went smoothly. However, there are some areas where your code could be enhanced:

for (let i = 0; i < json.reservations.length; i++) {
    if (json.reservations[i].resources !== null) {
        let reservation = json.reservations[i];
        for (let j = 0; j < reservation.resources.length; j++) 
            {
            let resource = reservation.resources[j];

            if (resource.type === "room") {                                     
                 rooms.push(resource.code + resource.name);                                
            }                                   
        }
    }
}

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

Tips for accessing a web service using only an HTML file

I am a newcomer to web services and I am working on creating a simple REST web service in Java for a basic login application. Here is the code: Server side: package com.testingws.webservices; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax ...

Assign the initial pointer of a 2D array to another pointer

As a newcomer to C, I may not be using the correct terminology when it comes to memory allocation. For example, let's say I have a function like this one, which returns a pointer to a pointer of integers. int **foo(){} //The functionality of this fun ...

Retrieving Specific Node Value in Array From XML Document

In my JavaScript function, I have a variable named "result". The value of the variable "result" is an XML. I need to create an array containing only the values of the opportunityid (highlighted in the image). How can I extract the particular node value ...

What causes TypeScript to generate an error when using two array of object types, but not when using the shape of both?

There are two basic types of data available: type DataA = { percent: string; exchange: string; }; type DataB = { price: number; exchange: string; }; I'm puzzled as to why TypeScript gives errors when I try to use both types together: const ...

Storing an item in the list using localStorage

Creating a dynamic list that utilizes the localstorage feature to save JSON array data has presented me with a challenge. The error displayed in Firebug is as follows: SyntaxError: JSON.parse: unexpected keyword var cli=JSON.parse(table[i]); Below is ...

Execute a JavaScript function prior to initiating an AJAX request

To streamline the process of making AJAX calls in my .NET project, I have developed a function called checkConnection that checks for internet connectivity before each call. However, currently, I am manually calling this function on every button click that ...

Continuously running loop to retrieve data

I've been working on a function that retrieves data from the backend and then assigns it to the state for display in a web browser. Although everything seems to be functioning correctly, I've noticed that every time I make a request, the function ...

Creating an empty array inside a Python function is a straightforward task

I need help with a function that extracts a specific column of data from a parent array and stores it in a new blank array. I am unsure how to make the function create this new array for the extracted data. The function includes two variables, "title" and ...

Transform a JSON POST into a Python list

Hey everyone, I have received a list from a JSON post. Here's the JSON: {"Array":"[(1, 2), (1, 3), (2, 3), (3, 4), (3, 5), (4, 5), (4, 6), (5, 6), (6, 7)]"} I'm looking to transform it into this format: type<class 'li ...

Reduce the combined character value of the title and excerpt by trimming the excess characters

I am seeking a solution to trim the total character count of a post title and excerpt combined. Currently, I can individually adjust the excerpt through theme settings and the post title using JavaScript. However, due to varying title lengths, the height ...

Guide for bringing in a complete npm library into React Native beyond just a single file access

Currently, I am facing an issue with importing the sjcl library into my project. Even though there are multiple files within the library, I am only able to import one file successfully. This is what I have tried from the command line: npm install sjcl -- ...

What is the best way to save a user's text input as separate elements in a String[] array

I have a private String[] teamName; and I am trying to store a user input string into it. However, when I try to do this by setting teamName[team] equal to keyboard.nextLine(), I encounter a null exception error. Why is this happening? Here is the code sn ...

"Error: Unable to determine the type id during the deserialization process" encountered while attempting to deserialize a subclass

I am currently working on integrating JsonSubTypes into my project and I would like to implement a graceful handling mechanism for unrecognized subtypes. The version of Jackson that I am using is 2.9.7, and upgrading is not an option due to dependencies on ...

I'm curious about how to properly escape single quotes when passing a variable in a Java argument call using Karate DSL. Can you help

As part of our API project at work, I am looking to incorporate database calls into our end-to-end process. One challenge I am facing is how to handle single quotes within a variable that is passed as an argument in an assert method. I have attempted the f ...

Double execution issue with jQuery radio button change event function

I have a simple function on my website that triggers when radio buttons are changed: $( 'form .radio_buttons' ).change( doTheFunction ) However, I recently noticed that the function is running twice whenever a change occurs. After some ponderin ...

Updating double quotes within a JSON string in a Freemarker template file

When working in an action class, I retrieve a list of beans using the conventional method. To convert this object list into a JSON string, I utilize Gson and it functions correctly as shown below: "{ "employees" : [{ "firstName":"John" , "lastName":"Doe" ...

What mechanisms do frameworks use to update the Document Object Model (DOM) without relying on a

After delving into the intricate workings of React's virtual DOM, I have come to comprehend a few key points: The virtual DOM maintains an in-memory representation of the actual DOM at all times When changes occur within the application or compo ...

How to Identify Duplicates in Arrays, Dictionaries, or Sets Using SWIFT

After researching Sets and Arrays, I discovered that a Set cannot store duplicate values (Ints, Strings, etc). Given this information, if we use the method of converting an Array to a Set to find a duplicate Int in an array, why don't we encounter an ...

How can I assign multiple values to a Pandas column containing an np.array data type?

I am working with a series of Numpy arrays in Pandas, structured like this: col1 col2 col3 0 1 a None 1 2 b [2, 4] 2 3 c None The array [2, 4] should actually be np.array([2, 4]). Now I am facing the task of filling in th ...

Automatically switch slides and pause the carousel after completing a loop using Bootstrap 5 Carousel

Seeking assistance with customizing the carousel functionality. There seems to be some issues, and I could use a hand in resolving them. Desired Carousel Functionality: Automatically start playing the carousel on page load, and once it reaches the end of ...