Finding the final element within a JavaScript object or associative array

Currently working on a JavaScript project that involves pulling in multiple JSON files to use in graphs. The challenge is identifying when the end of an associative array has been reached within a loop using $.each() (jQuery) so that the next JSON file can be triggered. I've come across solutions for single-tiered objects, but what about multi-tiered objects? How can the last element know it's the final one?

For example, here's a snippet of the JSON data I am dealing with:

{
    "Network":{
        "Hardware":262464,
        "Software":53016,
        "Internal Personnel":440202,
        "External Personnel":188658,
        "Outside Services":1344100,
        "Facilities and Overhead":16172,
        "Other":92588,
        "Total":2397200
    },
    "Wide Area Network":{
        "Hardware":75600,
        "Software":18900,
        "Internal Personnel":132300,
        "External Personnel":56700,
        "Outside Services":315000,
        "Facilities and Overhead":6300,
        "Other":25200,
        "Total":630000
    }
}

Below is a simplified version of the loop structure used to process this JSON data:

function buildColumns(array, parent) {
    $.each(array, function(key, value) {
        var newParent = $('<column>'); 
        $('<columnBox>').append($('<h2>').html(key)).append(newParent).appendTo(parent);
        if(value instanceof Object) buildColumns(value, newParent);     
    });
}

The loop above functions in a pseudo-recursive manner, although its final implementation may vary. Stay tuned!

Answer №1

If you want to determine the number of elements in an array, you can simply access the length property.

For example, if you have an array called array, array.length will give you the total number of items it contains.

When it comes to objects, you can use the following method:

Object.keys(jsonObject).length

In case you're unsure whether you are dealing with an array or an object, you can create a count method for objects to count their children:

Object.prototype.count = function() {
  oCount = 0; 
  for(var curObj in this) 
    if(curObj.hasOwnProperty(prop)) oCount++; 
  return oCount;
};

You can then call this method like so:

console.log(jsonObject.count());

Answer №2

The order in which fields appear in JavaScript objects may vary and is not guaranteed to be consistent across different browsers or over time. For more information, refer to this link.

As a result, the last item in an object is not always fixed.

If you require control over the order of items, consider transforming your object into an array, like so:

{
    "Network": [
         [{"Hardware":262464}],
         [{"Software":53016}],
         //  ...
    ],
    "Wide Area Network":[
        [{ "Hardware":75600}],
        // ...
    ],
    // ...
}

She

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

Handling exceptions in Node.js is an essential part of writing reliable

Just a quick question: I seem to be dealing with an incorrect endpoint, and every time I run the code below, it results in an exception being thrown client.post("http://WrongEndPoint", [], function (data, response) { console.log("data:", data, "respo ...

Javascript - Relocating a file to a different folder in a node.js environment

I am looking to duplicate a file and relocate it within the directory structure. Current file location: Test.zip -> Account/Images/ -account.png -icon.png -flag.png . ...

Creating dynamic variable names in Jquery by combining strings and numbers

Hey there, I'm really stuck and in need of a solution for the issue I've encountered. Currently, I have a script that sends an Ajax GET request and retrieves JSON data. The data is successfully returned, but when I try to loop through it, that&a ...

In Angular 2 templates using Typescript, there is flexibility with type enforcement in the code, allowing for a more

I have been following this particular tutorial Check out the code snippet below HTML <li *ngFor="let hero of heroes" (click)="onSelect(hero.id)"> <span class="badge">{{hero.id}}</span> {{hero.name}} </li> TS file selectedHer ...

I am having trouble scrolling through the main content when the side-drawer is open. How can I fix this issue?

When the sidebar is opened, I am facing issues with the main content scroll and certain fields such as select options and search bar not functioning properly. I have included the main content in the routes from which it is being loaded. However, the scroll ...

Creating a circular sun in Opengl and three.js: a step-by-step guide

Currently, I am working on enhancing an atmospheric shader based on the glsl-atmosphere library while using three.js. Initially, I applied these shaders to a sphere and achieved excellent results :) The original shaders lacked sun drawing elements, so I ...

"Passing a byte array from a C++ dynamic link library to C sharp programming language

I need help extracting a byte array from a DLL written in C within my C# program. This DLL is designed to interact with a National Instruments USB-8451. The specific function I'm attempting to utilize returns the array pointer as an output parameter. ...

Leveraging the api.call function to parse JSON data in a nodejs

I'm currently working on extracting data from a JSON response obtained through an API. Although I am able to stringify the response, I'm facing difficulties in parsing the JSON data and specifically retrieving the value of "display_name" into a v ...

Video background mute feature malfunctioning

I've searched through numerous resources and reviewed various solutions for this issue, yet I still haven't been able to figure it out. Could someone please guide me on how to mute my youtube embedded video? P.s. I am a beginner when it comes to ...

How to send JSON data using HTTP POST in iOS?

My attempt at this code is resulting in an unauthorized error being returned AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; [manager setRequestSerializer:[AFJSONRequestSerializer serializer]]; [manager.requestSeriali ...

What is the process for converting a date to a string such as "One Days Ago" or "Minutes Ago" in IOS?

I created an application that utilizes JSON parse data. Within this data, there is a date in the format "2014-12-02 08:00:42". I then transform this date into the format "12 FEB 2014" as shown below: NSDateFormatter * dateFormatter = [[NSDateFormatter all ...

Storing the radio button's selected value in local storage using Vue JS

I have a pair of radio buttons that are linked together to accept a boolean value, either true or false. I am trying to implement a functionality where the selected value is stored in local storage. For example, if true is chosen, then true will be saved i ...

How can I retrieve a PDF from a URL provided by the server using AngularJS?

Is it possible to automatically download a PDF file from a URL received through a $http GET() request from the server? The $http request is triggered by clicking a button on the front-end, and upon successful completion of the request, the URL where the PD ...

Troubleshooting a problem with the skybox texture in Three.js

I am currently experimenting with creating a basic Skybox using Three.js, but I've encountered an issue where the texture I'm applying to the cube is only visible on the outside and not on the inside. Below is the code for my skybox: const path ...

Guide on converting a material datepicker date value into the format "MM-DD-YYYY" in Angular 6

I need help formatting the date below to MM-DD-YYYY format in my Angular 6 project. I've checked out various solutions on SO and other websites, but so far, none have worked for me. Currently, I am using Material's Angular DatePicker component. ...

Guide on utilizing a variable within req.body in Node.js

My goal is to extract data from a dynamically generated form, but I am unsure of how many rows will be generated. Here is the form using EJS: <form action="/attendance-data" method="post"> <% var i=0 %> <% rows.forEach(function(item){ ...

Stopping the Vimeo player at the end of every Cycle slide

I am currently working on a project where I need to pause Vimeo players in each Cycle slide. I have successfully achieved this by declaring them individually in my script here: $(function() { var iframe1 = $('#player1')[0]; var iframe2 = ...

Creating a Matrix-style display of 2D arrays using Python

If I possess a matrix within a numpy array in Python In [3]: my_matrix Out[3]: array([[ 2., 2., 2., 2., 2., 2., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 2., 2., 2., 2., 0., 0., ...

Retrieving elements from a JSON string within a foreach loop

@foreach (var fieldset in Model.Content.GetPropertyValue<ArchetypeModel>("MainMenuDT")) { <li>@fieldset.GetValue("linkObj")</li> } this displays: [ { "caption":"gjhg", "link":"http://localhost:2081/", "newW ...

Transfer elements between arrays by maintaining the original reference

Looking for help with updating the indices of array1 in this scenario. Any suggestions on how to make the indices of array2 reference the indices of array1? http://jsfiddle.net/y8rs56r3/ var array1 = [ {num:"one"}, {num:"two"}, ...