Utilizing JavaScript to Extract Targeted Information from a JSON Object

Looking to extract specific data from my JSON response with the following structure;

{
   "status": "success",
   "reservations": [
      {
         "id": "26630",
         "subject": "Subject",
         "modifiedDate": "2017-05-16T06:05:12",
         "startDate": "2017-05-16T08:00:00",
         "endDate": "2017-05-16T09:45:00",
         "resources": [
            {
               "id": "2408",
               "type": "student_group",
               "code": "groupCode",
               "name": "groupName"
            },
            {
               "id": "3020",
               "type": "realization",
               "code": "realizationCode",
               "name": "realizationName"
            },
            {
               "id": "48",
               "type": "room",
               "code": "roomCode",
               "parent": {
                  "id": "2",
                  "type": "building",
                  "code": "buildingCode",
                  "name": "buildngName"
               },
               "name": "RoomName (PC)"
            }
         ],
         "description": ""
      },
      {
         "id": "21173",
         "subject": "subjectName",
         "modifiedDate": "2017-05-16T06:05:20",
         "startDate": "2017-05-16T08:00:00",
         "endDate": "2017-05-16T16:00:00",
         "resources": [
            {
               "id": "3115",
               "type": "realization",
               "code": "realizationCode",
               "name": "realizationName"
            },
            {
               "id": "2584",
               "type": "student_group",
               "code": "groupCode",
               "name": "groupName"
            },
            {
               "id": "52",
               "type": "room",
               "code": "roomCode",
               "parent": {
                  "id": "2",
                  "type": "building",
                  "code": "buildingCode",
                  "name": "buildingName"
               },
               "name": "roomName (classroom)"
            }
         ],
         "description": ""
      }
   ]
}

After parsing it as an object using JSON.parse() and looping through it using for-loops:

var json = JSON.parse(data.responseText);

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 reservations = json.reservations[i];
             var resources = json.reservations[i].resources[j];  

         }                              
     }
}

The task is to extract the room names before the key name "description":

"name": "roomName (PC)"
"name": "roomName (classroom)"

While I've kept the example JSON response short, in reality there are multiple room names. The goal is to retrieve all room names from the JSON response body, add them into an array, and display them chronologically like so;

roomName (PC)
roomName (classroom)

I'm seeking a fast and efficient method to achieve this.

Answer №1

Here is a method you can utilize:

const lists = data.reservations
  .filter(reservation => reservation.resources)
  .map(reservation =>
    reservation.resources.map(resource => resource.name)
  )
;

const names = [].concat.apply([], lists);

The technique for flattening an array was sourced from the following query: Merge/flatten an array of arrays in JavaScript?

Answer №2

To start, you can loop through the json.reservations array using Array.prototype.forEach(). Then, iterate over r.resources and utilize Array.prototype.push() if the condition

new RegExp(/roomName/, 'i').test(r.name)
is met.

It's important to note that in your json array, some "name": "roomName (classroom)" entries are lowercase while others like "name": "RoomName (PC)" are uppercase. The Regular Expression used will be case-insensitive due to the flag i, and ultimately RegExp.prototype.test() will verify if roomName exists within r.name.

See the code snippet below for implementation:

var json = {"status": "success","reservations": [{"id": "26630","subject": "Subject","modifiedDate": "2017-05-16T06:05:12","startDate": "2017-05-16T08:00:00","endDate": "2017-05-16T09:45:00","resources": [{"id": "2408","type": "student_group","code": "groupCode","name": "groupName"},{"id": "3020","type": "realization","code": "realizationCode","name": "realizationName"},{"id": "48","type": "room","code": "roomCode","parent": {"id": "2","type": "building","code": "buildingCode","name": "buildngName"},"name": "RoomName (PC)"}],"description": ""},{"id": "21173","subject": "subjectName","modifiedDate": "2017-05-16T06:05:20","startDate": "2017-05-16T08:00:00","endDate": "2017-05-16T16:00:00","resources": [{"id": "3115","type": "realization","code": "realizationCode","name": "realizationName"},{"id": "2584","type": "student_group","code": "groupCode","name": "groupName"},{"id": "52","type": "room","code": "roomCode","parent": {"id": "2","type": "building","code": "buildingCode","name": "buildingName"},"name": "roomName (classroom)"}],"description": ""}]},
    result = [],
    regex = new RegExp(/roomName/, 'i');

json.reservations.forEach(function (r) {
  r.resources.forEach(function (r) {
    regex.test(r.name) && result.push({
      name: r.name
    });
  });
})

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

To achieve this, a simple solution is as follows:

let data = {
   "status": "success",
   "results": [
      {
         "id": "111",
         "name": "Name 1"
      },
      {
         "id": "222",
         "name": "Name 2"
      }
   ]
}

let newData = [];
data.results.forEach(function(result) { 
    newData.push(result.name);
});
console.log(newData); //prints the desired array

Answer №4

const data = "{ \"status\": \"success\", \"reservations\": [ { \"id\": \"26630\", \"subject\": \"Subject\", \"modifiedDate\": \"2017-05-16T06:05:12\", \"startDate\": \"2017-05-16T08:00:00\", \"endDate\": \"2017-05-16T09:45:00\", \"resources\": [ { \"id\": \"2408\", \"type\": \"student_group\", \"code\": \"groupCode\", \"name\": \"groupName\" }, { \"id\": \"3020\", \"type\": \"realization\", \"code\": \"realizationCode\", \"name\": \"realizationName\" }, { \"id\": \"48\", \"type\": \"room\", \"code\": \"roomCode\", \"parent\": { \"id\": \"2\", \"type\": \"building\", \"code...
<p>(2) ["RoomName (PC)", "roomName (classroom)"]0: "RoomName (PC)"1: "roomName (classroom)"length: 2__proto__: Array(0)</p>
    </div></answer4>
<exanswer4><div class="answer" i="44000268" l="3.0" c="1494923417" a="U3ViaGFicmF0YSBNb25kYWw=" ai="8013737">
<pre><code>const jsonString = "{ \"status\": \"success\", \"reservations\": [ { \"id\": \"26630\", \"subject\": \"Subject\", \"modifiedDate\": \"2017-05-16T06:05:12\", \"startDate\": \"2017-05-16T08:00:00\", \"endDate\": \"2017-05-16T09:45:00\", \"resources\": [ { \"id\": \"2408\", \"type\": \"student_group\", \"code\": \"groupCode\", \"name\": \"groupName\" }, { \"id\": \"3020\", \"type\": \"realization\", \"code\": \"realizationCode\", \"name\": \"realizationName\" }, { \"id\": \"48\", \"type\": \"room\", \"code\": \"roomCode\", \"parent\":...
var array = [];  
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 resource = json.reservations[i].resources[j];
             if (resource.type === "room") {
                 if (array.indexOf("code")) {
                     array.push(resource.name);
                 }                                     
             }                                                                                         
         }

     }
}
 console.log(array);

output in console. Please review..

(2) ["RoomName (PC)", "roomName (classroom)"]0: "RoomName (PC)"1: "roomName (classroom)"length: 2__proto__: Array(0)

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

Working with a complex JSON structure in JavaScript exemplifies the use of loops

I am currently utilizing json.data.schedules[0].liveVideoList, json.data.schedules[1].liveVideoList, json.data.schedules[2].liveVideoList and so forth. Can someone please guide me on how to implement a loop to retrieve all paths? Here is the code in scri ...

Difficulty arises when using relative paths with XMLHttpRequest.send

Having difficulties with a basic task here. I'm in the process of creating a website without using a server, and I've hit a snag when it comes to accessing files via XMLHttpRequest. Looking at the example code provided below, you'll see tha ...

Step-by-step guide to utilizing instance functions in AngularJS

Recently I started working with angular in my project but I'm struggling to figure out how to access instance functions from the original code. Here is a snippet of my function: $scope.collapsedrow = true; $scope.PlusClick = function(event) ...

Is my HTML <h1> text not updating properly? I'm wondering if I linked app.js correctly

I'm currently learning the basics on a new machine and facing an issue where I am unable to modify the text within the header. It appears that the app.js file might not be properly connected to my index.html file. Within the app.js file, I have the f ...

How can I dynamically update the value of an ng-option based on the selection of another ng-option?

My application has 2 select option boxes. The first box contains a list of countries, and I want the second box to update its values based on the selection made in the first box. For instance, if I choose India from the first select box, the second select ...

What is the best way to gather the contents of several textboxes and save them in a single variable?

I've been working on a page that should calculate total hours worked, but unfortunately, I'm facing issues with the output. I've tried using both querySelectorAll and getElementsByTagName by switching the class tag to the name in the textbox ...

Struggling to configure Velocity Js?

After attempting to use Velocity Js for the first time, I encountered some issues while trying to create a navigation menu. Despite having functioning code and animations, the menu failed to open. I followed the instructions on the Velocity JS site by incl ...

Having trouble connecting Nextjs with ChromaDB?

I am encountering issues while trying to establish a connection with the Chromadb vector database in Nextjs. The objective is to store user-generated content in Chromadb. Below is the code snippet I am utilizing along with its dependencies: Dependencies V ...

Challenges with Loading Picasso Images in Recycler View

Whenever I click on card view items, the images do not display even though the data is loaded correctly using JSON and Picasso. Can anyone help solve this issue with your expertise in the Picasso library? public class SeconActivity extends Activity { Re ...

Implementing inline styles in the HEAD section of a Next.js website

I currently have a blog hosted on Jekyll at , and I'm looking to migrate it to Next.js. My unique approach involves embedding all the styles directly into the HEAD element of each HTML page, without utilizing any external stylesheet files. However, wh ...

Using NextJS to fetch data from an API after a form submission

Struggling with integrating an API call in my NextJS application, specifically when submitting a form. I keep encountering a random error upon submission, Error: Search(...): Nothing was returned from render. This usually means a return statement is missin ...

Draggable object animation in VueJS allows for smooth movement of

I'm currently working on developing draggable objects in Vue.js from scratch, but I've encountered two issues. After dragging, the object quickly snaps to the target coordinates without any transition effect. I attempted to eliminate the &apos ...

Dealing with cascading jQuery deferred callsHere are some guidelines on

When I have a function that needs to retrieve data and return a promise, I often find myself making multiple requests one after another. This results in nested deffered calls where the last call resolves on the deferred object that the function ultimatel ...

Updating a particular element in a JSON array with Python

Currently, I'm in the process of developing a discord bot that keeps track of players' Twitch Streams and promotes their streams when they go live. I've successfully set everything up and am utilizing a JSON file to store streamers' Tw ...

Convert a number to binary in JavaScript, but display the result as infinity

data = parseInt(num); bin =0; pow=1; var rem=0 ; while(data != 0){ rem = data % 2; data = data / 2; bin = rem * pow + bin; pow = pow *10; } document.write(bin); I encountered an issue with my JavaScript code. Even though the example should output 11011 ...

Generating arrays dynamically with JavaScript

I'm attempting to dynamically generate an array from another array in JavaScript. The task at hand involves taking a string that represents a mathematical literal expression, such as '2a + 3b + 4a + 5c', and splitting it into an array contai ...

Leveraging JQuery to retrieve JSON data from a local file

I am currently working on retrieving a list of JSON objects (products) from a local file using Jquery and then storing all of these objects in a single array named allItems. The file is located in the same directory as the code, and it is named "allItems.j ...

AngularJS Error: Cannot access the property '$scope' as it is undefined

I encountered an issue with my angularJS code and I'm unsure of the cause. I attempted to utilize the $inject Property Annotation method as detailed in this guide The error message "Uncaught TypeError: Cannot read property '$scope' of undef ...

Get a hold of a Linkedin profile

When attempting to download most web pages, everything works fine. However, when trying to download a specific LinkedIn page, it seems to output a lot of JavaScript code. from bs4 import BeautifulSoup import requests url = 'https://www.linkedin.com/ ...

The hyperlink does not function properly when included within an <input type=button> element

I have encountered an issue with the code below. In my project, I have a search bar along with some buttons. Currently, only the hyperlink of the search button is functioning correctly. The other buttons seem to redirect to the same link as the search bu ...