Using JavaScript, extract individual objects from a JSON object

Recently, I've been tasked with displaying items from a JSON-file in a well-organized manner. However, the format of the JSON file is unfamiliar to me. The code snippet provided below pertains to this task:

function readFile(file) {
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if (rawFile.readyState === 4 && rawFile.status === 200)
        {
            window.openedFile = JSON.parse(rawFile.responseText);
            console.log(JSON.stringify(openedFile, undefined, 4));
            createList();

        }
    };
    rawFile.send();
}


function createList() {
    var table = document.createElement('table');
    var body = document.createElement('tbody');

    for (var i = 0; i < openedFile.sites.length; i++) {
        var item = document.createElement('tr');
        var colSite = document.createElement('td');
        colSite.appendChild(document.createTextNode(openedFile.sites[i].name));
        item.appendChild(colSite);
        body.appendChild(item);
    }

    table.appendChild(body);
    document.getElementById('list').appendChild(table);
}

Unfortunately, it seems that the code isn't working properly as it keeps indicating that the array "sites" is empty. The altered output of the JSON-file displayed on the console looks somewhat like this:

{
    "sites": {
        "1007": {
            "id": 1007,
            "name": "Location B",
            "devices": {
                "p3": {
                    "name": "p3",
                    "version": "5"
                }
            }
        },
        "1337": {
            "id": 1337,
            "name": "Location A",
            "devices": {
                "p2": {
                    "name": "p2",
                    "version": "5"
                },
                "p1": {
                    "name": "p1",
                    "version": "5"
                }
            }
        }
    },
}

Upon modifying the JSON-file by adding [] brackets after sites and eliminating "1007" and "1337," the structure conforms to what I'm accustomed to (an ordinary array), which resolves the issue momentarily. However, I suspect this approach may not be permissible and poses a challenge when extracting device information. Any suggestions or assistance would be greatly appreciated. In essence, I'm seeking an alternative that doesn't involve altering the JSON-file.

Answer №1

In the realm of programming, numbers like 1007 and 1337 are unique identifiers associated with the entity known as sites. To analyze these properties, one can employ a technique called a for-in loop to systematically navigate through each attribute within the object.

var sites = openedFile.sites;
for(var site in sites){
    console.log("Key: ", site);
    console.log("Value: ", sites[site]);
}

Answer №2

The concept of "Sites" is treated as an object rather than an array, meaning you should loop through the properties of the object and not iterate over the elements of an array.

To retrieve a list of these properties, utilize Object.keys() which will return an array containing the property names.

Once you have this array, iterate through it and access each element (property name) to work with the original object's properties.

Below is an example that demonstrates this approach by simply logging the object's name (you already have the extraction part):

function generateList() {
   var keysArr = Object.keys(openedFile.sites); // obtain the array of property keys
   for (var key of keysArr) { // loop through the array of property keys
    console.log(openedFile.sites[key].name); /* access properties using keys from the original object */
  }
} 

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

Make sure to declare rest parameters first when using Typescript

I am dealing with a function that takes in multiple string arguments and one final argument of a complex type, which is called Expression. This particular code looks like this in JavaScript: function layerProp(...args) { const fields = args.slice(0, -1) ...

Discover the sub strings that fall between two specified regular expressions

I am looking for a way to extract substrings from a string that are between two specified regex patterns. Here are a few examples: My $$name$$ is John, my $$surname$$ is Doe -> should return [name, surname] My &&name&& is John, my & ...

Dividing an AngularJS module across multiple iFrames on a single webpage

Currently, I am working on a web application that consists of 1 module, 5 pages, and 5 controllers. Each HTML page declares the same ng-app. These pages are loaded within widgets on a web portal, meaning each page is loaded within an iFrame in the portal. ...

Utilizing the jq tool in Unix, convert complex JSON data with multiple levels into a CSV file

I have a complex JSON structure as shown below: { "id": "id123", "details": { "prod": "prod123", "etype": "type1" }, "accounts": [ { ...

Utilizing PHP loops with the integration of a Datetimepicker

When using datetimepicker javascript for bootstrap, I encountered an issue where the instance works fine if there is only one input field or if it's the first of multiple fields. However, when there are multiple fields, the datetimepicker does not wor ...

Mapping Realm objects to persist any type of data This is a unique representation

As I develop an application, I encounter that both schemas are identical (DB & LocalDB). The convenience of Realm parsing the JSON received from the server with just one line of code is amazing. if let JSON = response.result.value { let realm = try! ...

The WCF Rest Service consistently returns a deserialization value of 0 without fail

In my WCF Rest service, there is a method that accepts multiple parameters: [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json)] StatusMessage DoSomeWork(short myId ...

how to combine a string in JavaScript using a prefix and suffix

Anion Gap Body Surface Area (BSA) Creatinine Clearance Stack Overflow i want to add "String" Before Text and "String" after end of text. I have Following expression which runs perfectly in excel:- =CONCATENATE("",B1,"") Output:- <string>Anion Ga ...

The functionality of Jquery UI is not compatible with version 1.12

Incorporating jQuery UI into my current project has presented some challenges. Both the jquery-ui.min.css and jquery-ui.min.js files are version 1.12, so I opted for the latest jQuery version, jquery-3.2.1.min.js. Specifically, I decided to test the datep ...

What is the best way to organize a flatlist for rendering?

I'm struggling with separating some flat-lists into different components. How can I arrange the rendering of the flat-list like the sample form (Picture "Sample UI")? I've tried, but it's not working correctly as it renders flat list A first ...

Having trouble inserting a Button element into a li parent element

I'm attempting to insert a button inside an li element using the .appendChild method, but for some reason, it's not working. I also tried changing the parent's inner HTML. let inputElement = document.querySelector('#input'); let ...

Javascript's ReferenceError occasionally acts inconsistently when using Firefox's scratchpad

While delving into the world of Javascript for learning purposes, I encountered an unexpected behavior. Let's explore this scenario: function hello(name) { let greet = 'Hello ' alert(greet + name) } hello('world') alert(gree ...

Discovering ways to examine a React tree, view the props and state of components on Internet Explorer 11

After installing the React Developer Tools extension for Firefox and Chrome, I have been able to successfully utilize them. However, my struggle lies in not being able to locate a similar extension for Internet Explorer 11. Unfortunately, my application i ...

The issue of Jquery selectors not functioning properly when used with variables

Currently working on a script in the console that aims to extract and display the user's chat nickname. Initially, we will attempt to achieve this by copying and pasting paths: We inspect the user's name in the Chrome console and copy its selec ...

Utilizing various layouts in ASP.NET MVC with AngularJS

I am setting up two different layouts, one for visitors and one for management. Routes: app.config(['$routeProvider', function ( $routeProvider) { $routeProvider .when('/', { templateUrl: 'Home ...

Sending POST Requests with Next.js Version 14

How can I send a POST request using axios in Next.js 14, I prefer axios but fetch is also okay. I have been getting an AxiosError: Network Error when I try to use axios and TypeError: fetch failed when using fetch. However, it works fine with Postman. I ...

What is the best method for transforming this json data into a yml format?

Can someone assist me with converting a list of dictionaries into a .yml file? input = [ { 'id': 1, 'coordinates': [ [34, 31], [235, 31], [34, 97], [235, 97] ...

What is the best way to implement a scrollbar in a specific div rather than the entire window?

Hey everyone! So, I have this window in electronJS with a div where I'm dynamically adding elements using Javascript and the function --> document.createElement('section'). Here's the loop in Javascript to add these elements: for ( ...

Updating Key-Value pairs in an ArrayList using Angular 4

After importing json data into an arrayList and storing it in local-storage, the structure looks like this: [ { "id": 1, "name": "Albany", "manufacture": "Albany Superior Low Gi Sliced Brown Seed Bread 700g", "price": 1 ...

Tips for managing the number of items returned in a dataProvider using AS3

*Hey there! I'm looking to only display 100 items in a list component from a dataProvider, even if it contains more than 500 or even 1000 items. Specifically, I want the first 100 items with cameras on to be included, and then fill the rest to reach a ...