Ways to access childData within a specified key

Recently, I developed a script to organize data based on their moduleId.

Take a look at this sample json:

{
    "1": [{
        "id": 1,
        "moduleId": "1",
        "dropdownModuleName": "NL",
        "isDeleted": null,
        "createdBy": "1",
        "updatedBy": null,
        "dateCreated": "2018-09-19 17:37... etc.
    }],
    ...
}

To accomplish this task, I utilized the following script:

newBody = JSON.parse(body);

newJson = _.groupBy(newBody,function (o) {
    return o.moduleId
})
nBody = JSON.stringify(newJson)

My goal was to extract the dropdownModuleName,moduleId from the json after a successful ajax request. However, when I attempted to loop through the results, nothing appeared in my console...

Below is the code snippet for my ajax request:

 $.ajax({
     url:'/api/navbarToggleDropdownMenu/getall',
     type:'GET',
     dataType:'JSON',
     success:function (res) {
         console.log(res);
         for (var i = 0; i < res.length; i++) {
            console.log(res[i])
         }
    }
})

The first console log displayed the json as mentioned above, but the loop inside did not show any result.

Answer №1

try updating your loop to something similar to this

for (const key in res) {
  console.log(res[key]);
}

var res = {
    "1": [{
        "id": 1,
        "moduleId": "1",
        "dropdownModuleName": "NL",
        "isDeleted": null,
        "createdBy": "1",
        "updatedBy": null,
        "dateCreated": "2018-09-19 17:37:21",
        "dateUpdated": null
    }, {
        "id": 2,
        "moduleId": "1",
        "dropdownModuleName": "EE",
        "isDeleted": null,
        "createdBy": null,
        "updatedBy": null,
        "dateCreated": "2018-09-19 18:01:39",
        "dateUpdated": null
    }, {
        "id": 3,
        "moduleId": "1",
        "dropdownModuleName": "SA",
        "isDeleted": null,
        "createdBy": null,
        "updatedBy": "1",
        "dateCreated": "2018-09-19 18:01:46",
        "dateUpdated": "2018-09-19 18:10:02"
    }],
    "4": [{
        "id": 4,
        "moduleId": "4",
        "dropdownModuleName": "CON",
        "isDeleted": null,
        "createdBy": null,
        "updatedBy": "1",
        "dateCreated": "2018-09-19 18:01:56",
        "dateUpdated": "2018-09-19 18:13:33"
    }, {
        "id": 5,
        "moduleId": "4",
        "dropdownModuleName": "XPO",
        "isDeleted": null,
        "createdBy": "1",
        "updatedBy": null,
        "dateCreated": "2018-09-19 18:38:41",
        "dateUpdated": null
    }, {
        "id": 6,
        "moduleId": "4",
        "dropdownModuleName": "RG",
        "isDeleted": null,
        "createdBy": "1",
        "updatedBy": null,
        "dateCreated": "2018-09-19 19:13:00",
        "dateUpdated": null
    }],
    "5": [{
        "id": 7,
        "moduleId": "5",
        "dropdownModuleName": "REG",
        "isDeleted": null,
        "createdBy": "1",
        "updatedBy": null,
        "dateCreated": "2018-09-19 19:13:18",
        "dateUpdated": null
    }, {
        "id": 8,
        "moduleId": "5",
        "dropdownModuleName": "COM",
        "isDeleted": null,
        "createdBy": "1",
        "updatedBy": null,
        "dateCreated": "2018-09-19 19:13:28",
        "dateUpdated": null
    }, {
        "id": 9,
        "moduleId": "5",
        "dropdownModuleName": "BEE",
        "isDeleted": null,
        "createdBy": "1",
        "updatedBy": null,
        "dateCreated": "2018-09-19 19:13:35",
        "dateUpdated": null
    }, {
        "id": 10,
        "moduleId": "5",
        "dropdownModuleName": "CA",
        "isDeleted": null,
        "createdBy": "1",
        "updatedBy": null,
        "dateCreated": "2018-09-19 19:13:44",
        "dateUpdated": null
    }, {
        "id": 11,
        "moduleId": "5",
        "dropdownModuleName": "PPC",
        "isDeleted": null,
        "createdBy": "1",
        "updatedBy": null,
        "dateCreated": "2018-09-19 19:13:51",
        "dateUpdated": null
    }, {
        "id": 12,
        "moduleId": "5",
        "dropdownModuleName": "TIC",
        "isDeleted": null,
        "createdBy": "1",
        "updatedBy": null,
        "dateCreated": "2018-09-19 19:13:58",
        "dateUpdated": null
    }]
}

for (const key in res) {
    console.log(res[key])
}

Answer №2

If you encounter the message above, it may indicate an issue with

res[i]

The object 'res' is defined within curly braces. The ID is a property of 'res', but because numbers are not valid JavaScript identifiers or variable names, accessing it as res.1 won't work.

Consider introducing another level in the response using a different key?

Alternatively, try a different approach, such as iterating over properties e.g

for (var property1 in res) { 
    res[property1]; } // this is the value 
}

Answer №3

If you give this code a try, you may see the result displayed in your console:

Instead of using a for loop, consider replacing it with the following code snippet:

var responseObj = JSON.parse(JSON.stringify(res));
    $.each(responseObj.d, function (index, el) {
        console.log("Id:- "+el.id+" Module Id:- "+ el.moduleId
        +" Module Name:- "+el.dropdownModuleName);
});

Answer №4

To uncover the child value, employing a nested loop is essential. In this particular case, I utilized the $.each nested function and executed

console.log('moduleId-' + v.moduleId +' '+'dropdownModuleName-'+ v.dropdownModuleName)
.

var data = {
    "1": [{
        "id": 1,
        "moduleId": "1",
        "dropdownModuleName": "NL",
        "isDeleted": null,
        "createdBy": "1",
        "updatedBy": null,
        "dateCreated": "2018-09-19 17:37:21",
        "dateUpdated": null
    }, {
        "id": 2,
        "moduleId": "1",
        "dropdownModuleName": "EE",
        "isDeleted": null,
        "createdBy": null,
        "updatedBy": null,
        "dateCreated": "2018-09-19 18:01:39",
        "dateUpdated": null
    }, {
        "id": 3,
        "moduleId": "1",
        "dropdownModuleName": "SA",
        "isDeleted": null,
        "createdBy": null,
        "updatedBy": "1",
        "dateCreated": "2018-09-19 18:01:46",
        "dateUpdated": "2018-09-19 18:10:02"
    }],
    "4": [{
        "id": 4,
        "moduleId": "4",
        "dropdownModuleName": "CON",
        "isDeleted": null,
        "createdBy": null,
        "updatedBy": "1",
        "dateCreated": "2018-09-19 18:01:56",
        "dateUpdated": "2018-09-19 18:13:33"
    }, {
        "id": 5,
        "moduleId": "4",
        "dropdownModuleName": "XPO",
        "isDeleted": null,
        "createdBy": "1",
        "updatedBy": null,
        "dateCreated": "2018-09-19 18:38:41",
        "dateUpdated": null
    }, {
        "id": 6,
        "moduleId": "4",
        "dropdownModuleName": "RG",
        "isDeleted": null,
        "createdBy": "1",
        "updatedBy": null,
        "dateCreated": "2018-09-19 19:13:00",
        "dateUpdated": null
    }],
    "5": [{
        "id": 7,
        "moduleId": "5",
        "dropdownModuleName": "REG",
        "isDeleted": null,
        "createdBy": "1",
        "updatedBy": null,
        "dateCreated": "2018-09-19 19:13:18",
        "dateUpdated": null
    }, {
        "id": 8,
        "moduleId": "5",
        "dropdownModuleName": "COM",
        "isDeleted": null,
        "createdBy": "1",
        "updatedBy": null,
        "dateCreated": "2018-09-19 19:13:28",
        "dateUpdated": null
    }, {
        "id": 9,
        "moduleId": "5",
        "dropdownModuleName": "BEE",
        "isDeleted": null,
        "createdBy": "1",
        "updatedBy": null,
        "dateCreated": "2018-09-19 19:13:35",
        "dateUpdated": null
    }, {
        "id": 10,
        "moduleId": "5",
        "dropdownModuleName": "CA",
        "isDeleted": null,
        "createdBy": "1",
        "updatedBy": null,
        "dateCreated": "2018-09-19 19:13:44",
        "dateUpdated": null
    }, {
        "id": 11,
        "moduleId": "5",
        "dropdownModuleName": "PPC",
        "isDeleted": null,
        "createdBy": "1",
        "updatedBy": null,
        "dateCreated": "2018-09-19 19:13:51",
        "dateUpdated": null
    }, {
        "id": 12,
        "moduleId": "5",
        "dropdownModuleName": "TIC",
        "isDeleted": null,
        "createdBy": "1",
        "updatedBy": null,
        "dateCreated": "2018-09-19 19:13:58",
        "dateUpdated": null
    }]
}
$.each(data, function(key, value){
    $.each(value, function(k,v){
        console.log('moduleId-' + v.moduleId +' '+'dropdownModuleName-'+ v.dropdownModuleName)
    })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

The challenges of using Three.JS and Blazor: Solving Black Canvas and Console Errors in WebGL

Exploring the world of Blazor web assembly, I embarked on a project to harness the power of JSInterop with Three.JS to draw lines. Following the guidelines provided in their tutorials available Here, I diligently installed Three.JS using npm and webpack, w ...

Restoring byte arrays to their initial form on the hard drive in the C programming language

I've recently come across a challenge that some might find pointless, but it's been on my mind - how do I write a byte array back to its original file instead of executing it in memory? There is an abundance of information on executing in memory, ...

I am seeking guidance on implementing a 301 redirect within a Node JS project using an Express JS router. Can

Currently facing an issue with setting up a 301 redirect from 'domain.com' to 'www.domain.com' on my project hosted on Heroku Cloud. I have tried using Topic Search and Google for solutions, as well as other search engines, but haven&ap ...

Is there a way I can implement pagination on a bootstrap table that has its header positioned on the left side?

Recently, I stumbled upon this table on Stack Overflow and I am curious to learn how to incorporate pagination for every 5 entries. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link ...

Instant access to an interactive online platform

Is it feasible to create a shortcut from a webpage to my desktop for quick access? For instance, if a dynamic web page has 15 documents and I want to easily create shortcuts to them on my desktop by clicking on each one. I understand this is a brief quest ...

Find the variance between today's date and a selected date, then initiate the timer based on this variance

I have a grid containing data. I utilize the loadGrid() function to preload data or conditions before the grid finishes loading. When the active state is set to 1, my intention is to initiate a timer by calculating the difference between the current date ...

Discovering if an agent is a mobile device in Next.js

I am currently working with nextjs version 10.1.3. Below is the function I am using: import React, {useEffect, useState} from "react"; const useCheckMobileScreen = () => { if (typeof window !== "undefined"){ const [widt ...

What is the method for generating a popover in HTML when a user hovers over a button?

In this scenario, I have implemented two status buttons with different colors. The green button corresponds to "RUNNING" and the red button indicates "TERMINATED", which are fetched from JASON data. Upon hovering over the green status button, the text "RU ...

It appears that socket.io is having trouble initializing and is not able to recognize the io.configure method

Attempting to set up socket.io with node/express, encountering an error when using the io.configure method: io.configure(function() { ^ TypeError: Object #<Server> has no method 'configure' at Object.<anonymous> (/home/yz/webd ...

Tips for showing nested array values in Angular 8

I'm new to using angular and I'm attempting to display values from an array within another array in a table format. Here is my JSON array that I'd like to display in rows: { "data": { "Influencer": [ { ...

I'm looking to send a one-dimensional array to a PHP page using jQuery and Ajax - how can I achieve this?

I have a one-dimensional array that is dynamically filled and emptied based on checkbox selections. Here is an example of how the array looks: arrReservedSeats = ["1A", "3B", "5C", ...] My goal is to use this array in PHP to store the data in a database ...

Genvalidator: Validate forms by checking for checkbox selection

Currently, I am utilizing genvalidator to conduct tests on input fields within a form. One issue I am encountering is the inability to determine if a checkbox has been checked. Below are the settings for all fields: frmvalidator.addValidation("name","req ...

Getting Django post_save signal to work with AJAX query

After utilizing AJAX request to create an order, I also have a post_save signal that should trigger once the order has been saved. However, it seems like this signal is not being received during the AJAX request process. Is there a way to ensure that the ...

What is the most efficient method for executing over 1,000 queries on MongoDB using nodejs?

I have a task to run around 1,000 queries on MongoDB in order to check for matches on a specific object property. I must confess that my code is quite amateurish, but I am open to any suggestions on how to improve its efficiency. The current version works ...

Delivering numerous cfquery results to an AJAX request

I am in the process of creating a webpage that will utilize AJAX to make an API call upon submission of a webform. The AJAX call will then access a CFC (ColdFusion component) that contains a function responsible for calling a SQL stored procedure and passi ...

Navigating Perl: Unraveling the Mysteries of Accessing Hashes Within an

I have a unique Hash structure that I think refers to an array of hashes. I'm trying to figure out how to access the individual hash elements within this array. UPDATE: Here is the detailed hash structure $VAR1 = { 'CVE-2015-0677' =& ...

C#: How to Automatically Choose Dropdown Options Using Marionette Driver

Currently, I am utilizing Selenium Webdriver alongside C# bindings and transitioning from the outdated FirefoxDriver (pre-FF 47) to the newer Marionette driver (FF47 and above). The switch has been successful after encountering some initial challenges that ...

The Else clause is executing twice in the jQuery code

https://jsfiddle.net/mpcbLgtt/2/ Creating a function that adds card names to an array named deck and their IDs to another array called cardIds when a div with the class "card" is clicked. The cards available are: <div class='card' id=' ...

Create custom headers for a webm file in order to allow the playback of downloaded damaged media

Have you ever come across a website that seems to fetch .webm files from their server, some appearing like chunks of the file while others seem to be complete webm files? But when you try to play these files on a custom video player or any other player, th ...

Progress bar indicating the loading status of an AJAX script

I am facing a challenge with creating a progress bar in AJAX. The entire page is loaded through AJAX, and one of the webpage elements uses AJAX to fetch large rows from the database. I have attempted to implement a progress bar within this script using a ...