Tips for retrieving nested JSON objects

I'm struggling to access the nested JSON object values through iteration.

Even after attempting

console.log(test[0].Invoice[0].Cost.NO[0]);
, I still can't get it to work.

var test = [{
  "Invoice": {
    "NO": "869",
    "$$hashKey": "object:186"
  },
  "Cost": [{
    "NO": 183,
    "Amnt": 100
  }, {
    "NO": 184,
    "Amnt": 200
  }]
}, {
  "Invoice": {
    "NO": "698",
    "$$hashKey": "object:189"
  },
  "Cost": [{
    "NO": 110,
    "Amnt": 150
  }, {
    "NO": 142,
    "Amnt": 263
  }]
}];

console.log(test[0].Invoice[0].Cost.NO[0]);

Answer №1

It appears your code using

console.log(test[0].Invoice[0].Cost.NO[0]);
is not functioning correctly.

It seems that Invoice and Cost are objects on the same level (Cost is not nested within Invoice).

Refer to the example below for guidance on accessing them properly.

It is essential to have a good understanding of Arrays [] and Objects {}.

var test = [{
  "Invoice": {
    "NO": "869",
    "$$hashKey": "object:186"
  },
  "Cost": [{
    "NO": 183,
    "Amnt": 100
  }, {
    "NO": 184,
    "Amnt": 200
  }]
}, {
  "Invoice": {
    "NO": "698",
    "$$hashKey": "object:189"
  },
  "Cost": [{
    "NO": 110,
    "Amnt": 150
  }, {
    "NO": 142,
    "Amnt": 263
  }]
}];

// Accessing COST
console.log(test[0].Cost[0].NO);

// Accessing Invoice
console.log(test[0].Invoice.NO);

Answer №2

Here is the JSON data for you:

let data = [{
  "Invoice": {
    "Number": "869"
  },
  "Cost": [{
    "Number": 183,
    "Amount": 100
  }, {
    "Number": 184,
    "Amount": 200
  }]
}, {
  "Invoice": {
    "Number": "698"
  },
  "Cost": [{
    "Number": 110,
    "Amount": 150
  }, {
    "Number": 142,
    "Amount": 263
  }]
}];

console.log(data[0].Cost[0].Number);
will result in 183

If you are unfamiliar with JSON, you can use console.log(data) to verify the structure during development.

To iterate through the data, you can use a loop like the one explained here: https://www.w3schools.com/jsref/jsref_forEach.asp

Here is a simple example:

let myFunction = function(item, index){
    console.log(item.Cost[0].Number);
 }
 data.forEach(myFunction)

Answer №3

testing entails working with an array, so you must iterate through it.

During each iteration, you will receive an object with 2 properties: Invoice and Cost

Invoice is once again an object, so you only need to access the specific property you require

Cost is an array, meaning you need to iterate over each item, which are objects

var testing = [{
  "Invoice": {
    "NO": "869",
    "$$hashKey": "object:186"
  },
  "Cost": [{
    "NO": 183,
    "Amnt": 100
  }, {
    "NO": 184,
    "Amnt": 200
  }]
}, {
  "Invoice": {
    "NO": "698",
    "$$hashKey": "object:189"
  },
  "Cost": [{
    "NO": 110,
    "Amnt": 150
  }, {
    "NO": 142,
    "Amnt": 263
  }]
}];

testing.forEach(t=>{
  console.log("Invoice N°: " + t.Invoice.NO);
  t.Cost.forEach(c=>{
    console.log("- Cost N°: "+ c.NO + " - Amount: " + c.Amnt);
  });
});

Answer №4

Your statement is incorrect

test[0].Invoice[0].Cost.NO[0]

The correct format is

 test[0].Cost[0].NO

Since Invoice and Cost are properties of the same JSON object.

Please give this a try

  var test = [{ "Invoice": { "NO": "869", "$$hashKey": "object:186" }, "Cost": [{ "NO": 183, "Amnt": 100 }, { "NO": 184, "Amnt": 200 }] }, { "Invoice": { "NO": "698", "$$hashKey": "object:189" }, "Cost": [{ "NO": 110, "Amnt": 150 }, { "NO": 142, "Amnt": 263 }] }];

  console.log(test[0].Cost[0]);
 console.log(test[0].Cost[0].NO);
   

 

Answer №5

 let example = [{ "Invoice": { "NO": "869", "$$hashKey": "object:186" }, "Cost": [{ "NO": 183, "Amnt": 100 }, { "NO": 184, "Amnt": 200 }] }, { "Invoice": { "NO": "698", "$$hashKey": "object:189" }, "Cost": [{ "NO": 110, "Amnt": 150 }, { "NO": 142, "Amnt": 263 }] }];
        for (let e in example)
        {
            let obj = example[e];
            console.log(obj.Invoice.NO);
            console.log(obj.Invoice.$$hashKey);
            for (let cost in obj.Cost)
            {
                console.log("Cost Value: " + obj.Cost[cost].NO + " " + obj.Cost[cost].Amnt);
            }
        }

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

What are the steps to transforming a regular expression into a dynamic format?

I've developed a powerful regex that locates specific text within a lengthy string without spaces. Now I'm attempting to utilize it dynamically to search for various words, but I can't seem to make it function as intended. Check out my rege ...

The AnimationMixer is refusing to start playing the animation from the gltf file

I have successfully imported a model using three.js and it works fine. Now, I am trying to run animations from a GLB file. Although I can retrieve the animation names with three.js, the TJS library fails to play my animations. GLB FILE There are two anim ...

Retrieving a MongoDB collection using its unique ID

Here's a query that may seem straightforward. I have two collections in MongoDB - one named "users" with an objectId, and the other named "listings" which has the userId. I am looking to retrieve documents from the listings collection by searching fo ...

Unable to send data to Spring Controller from form submission

As a newcomer to Spring, I have been exploring tutorials online to enhance my knowledge. Recently, I developed a straightforward Spring MVC Login App utilizing AngularJS for the frontend and JSON for data posting to the Spring Controller. The login form I ...

What could be causing my ul list to not be populated by ajax?

To populate the ul list with data from PHP code on page load, you can use the following ajax function. I appreciate any help in advance, and please forgive me if my explanation is not precise as I'm new here. This post contains mostly code snippets. ...

Unable to conceal tab content upon clicking the identical tab

I recently implemented a tab system with panels that seems to be working well when switching between tabs. However, I'm facing an issue where clicking on the same tab does not hide the corresponding panel and reset the aria attributes as intended. I&a ...

Verifying the selection state of a dynamically generated checkbox with JavaScript

I have a table with checkboxes. Each time a button is clicked, I dynamically add new checkboxes to the table like so: var cell3 = row.insertCell(2); cell3.innerHTML = '<input type="checkBox" value=\"selected?\" style="cursor:poin ...

Stop javascript function from automatically invoking itself

I am new to php and javascript and currently working on using a session variable to keep track of a counter. I want the counter to increment on the next button click and decrement on the previous button click. The issue I'm facing is with the JavaScri ...

Object displaying no visible illumination

Recently, I've been experimenting with this project, and after some trial and error, I've managed to get things working to some extent. As a novice in JavaScript, I'm unsure if the issue I'm facing has a simple solution. The problem is ...

Node.js & Express: Bizarre file routes

It's quite strange how my local paths are functioning. Let me show you an example of my directory structure: public > css > bootstrap.css public > js > bootstrap.js templates > layout > page.ejs (default template for any page) tem ...

What is the best way to convert a JSON object into a C# object within a Xamarin Get API?

Below is a JSON object I have: { "Metadata": { "TotalRecords": 12, "CurrentPageSize": 2, "CurrentPage": 1, "TotalPages": 2 }, "Results": [ { "Id": 1, "OwnerId": "3be73a87-a977-467a-84c0", "OwnerName": "AV", ...

"Need to remove all chosen selections within an ng-repeat loop? Here's how

var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.cars = [{ model: "Ford Mustang", color: "red" }, { model: "Fiat 500", color: "white" }, { model: " ...

What is the best way to bring a string into my .tsx file using a relative reference from a module?

I am currently developing an online course on creating a website using StencilJS, NodeJS, and the IonicFramwork. As a newcomer in this field, I have encountered a challenging issue: In my project, the API "https://swapi.dev/api" is imported as a ...

The backend error message isn't triggering an alert!

My current issue involves using jQuery to execute a .php file. Whenever an error occurs in the backend, I want to display an alert message with the error details. However, when intentionally submitting with an error, no alert pops up and it just proceeds t ...

What is the JSON Schema counterpart to XSD's maxOccurs property?

I've been scouring the internet for hours, but I can't seem to find any examples that match my specific query. I have a condensed XSD schema like this: <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name= ...

Is it possible to save an HTML5 Canvas screenshot directly onto the page?

After browsing numerous tutorials on saving HTML5 canvas screenshots as images and opening them in new tabs, I'm wondering if there's a way to display the captured screenshot in a pre-set div on the SAME WEBPAGE. Any suggestions or solutions woul ...

What is the best way to execute a .js file with a Mocha suite repeatedly within a loop?

I have a collection of .js test files and I am looking for a way to execute the tests in each file multiple times. Ideally, I would like to run them 5 or 10 times consecutively. Even if it's just one file at a time, but running it multiple times. I a ...

Function useAppDispatch is missing a return type

.eslintrc.js module.exports = { root: true, extends: [ '@react-native-community', 'standard-with-typescript', 'plugin:@typescript-eslint/recommended', 'plugin:jest/recommended', 'plugin:p ...

Developing an npm library with ReactJs: A step-by-step guide

As a newcomer to React, I am eager to create my own npm library in ReactJS. Taking inspiration from my existing React project, the goal is to transform it into a package (or library) that can be easily integrated into other projects. This means allowing ...

AngularJS ng-repeat - cascading dropdown not refreshing

I'm dealing with an AngularJS issue where I'm trying to create a cascade dropdown like the one below: <div class="col-sm-2 pr10"> <select class="PropertyType" ng-controller="LOV" ng-init="InitLov(140)" ng-model=" ...