Accessing a specific JSON field in the JavaScript console

Having trouble extracting the value of StatusDescription from this JSON data structure. Despite multiple attempts, the result returned is consistently undefined. Below is a snippet of the JSON data:

 {
  "meta": {
    "a2": 200,
    "ta": "dasd",
    "asdd": "asdda"
  },
  "data": {
    "items": [
      {
        "id": "",
        "number": "",
        "origin_info": {
          "ItemReceived": "2021-10-02 02:07:49",
          "phone": 123456789,
          "trackinfo": [
            {
              "StatusDescription": "what i need",
              "Details": "",
              "substatus": "ok"
            },
   
            {
              "StatusDescription": "what i need",
              "Details": "",
              "substatus": "ok"
            }
          ]
        },
        "destination_info": null,
        "lastEvent": "grgrgrgrgr",
        "lastUpdateTime": "mewmemew"
      }
    ]
  }
}

This JSON data is being utilized in my NodeJS application within a file named myapp.js, and I am logging the output using console.log()

Answer №1

To access the StatusDescription, you need to loop through your items and their corresponding trackinfo. Give this a try.

const data = {
  "meta": {
    "a2": 200,
    "ta": "dasd",
    "asdd": "asdda"
  },
  "data": {
    "items": [
      {
        "id": "",
        "number": "",
        "origin_info": {
          "ItemReceived": "2021-10-02 02:07:49",
          "phone": 123456789,
          "trackinfo": [
            {
              "StatusDescription": "what i need",
              "Details": "",
              "substatus": "ok"
            },
   
            {
              "StatusDescription": "what i need",
              "Details": "",
              "substatus": "ok"
            }
          ]
        },
        "destination_info": null,
        "lastEvent": "grgrgrgrgr",
        "lastUpdateTime": "mewmemew"
      }
    ]
  }
}

const items = data.data.items.map(item => item)
const trackinfo = items.map(item => item.origin_info.trackinfo).flat()
console.log(trackinfo)
const statusDescription = trackinfo.map(trackinfo => trackinfo.StatusDescription)

console.log(statusDescription)

Answer №2

Give this a shot

Your provided JSON data has been saved in the variable json

var json = {
  "meta": {
    "a2": 200,
    "ta": "dasd",
    "asdd": "asdda"
  },
  "data": {
    "items": [
      {
        "id": "",
        "number": "",
        "origin_info": {
          "ItemReceived": "2021-10-02 02:07:49",
          "phone": 123456789,
          "trackinfo": [
            {
              "StatusDescription": "what i need",
              "Details": "",
              "substatus": "ok"
            },
   
            {
              "StatusDescription": "what i need",
              "Details": "",
              "substatus": "ok"
            }
          ]
        },
        "destination_info": null,
        "lastEvent": "grgrgrgrgr",
        "lastUpdateTime": "mewmemew"
      }
    ]
  }
}

You can access it as shown below

console.log(json.data.items[0].origin_info.trackinfo[0].StatusDescription);

Items is an array and we are selecting array element 0.

trackinfo is also an array where we are selecting array element 0.

You have the option to change the array index or iterate through to retrieve specific values.

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

Tips for dynamically loading fresh Google Adsense code with JavaScript without any user interaction

Recently, Google made a change in their ad code by replacing <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js</script> with <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygo ...

Java 8 Streams and Multi-level Grouping with GroupingBy

I am looking to create a JSON output structure as shown below { "account":{ "Alpha":{ "OLD":{ "long":"zerozerooneO", "short":"001O" }, ...

Troubleshooting issue with jquery.i18n.properties functionality

I am encountering an issue with implementing jQuery internationalization. I have included the files jquery.i18n.properties.js, jquery.i18n.properties-min.js, and jquery-min.js in my resources folder. In my jsp, I have added the following code: <script ...

Creating a production build with sourcemaps in Angular using the CLI

How can I preserve sourcemaps after the production build process? Currently, my command appears as follows: "build-prod": "ng build --app=release -prod && cp -R lang dist" I attempted to modify it to: ng build --app=release --sourceMap=true -prod && cp ...

Vue.js app does not have the capability to display JSON data as a table

I successfully fetched JSON data in my vue app from the endpoint '/v1/api/sse?raceId=1', but I'm struggling to convert this JSON into a table format. The JSON is displaying correctly, but I'm unsure how to structure it into a table. He ...

Having trouble retrieving the value of a custom directive attribute

My custom directive, named "mycomponent", has the following configuration: restrict: 'AE', templateUrl: 'template.html', scope:{ sTransactionType: '=transactionType', sStorageVariable: '=storageVariable&apos ...

Executing a function with a click, then undoing it with a second click

My goal is to trigger an animation that involves text sliding off the screen only when the burger icon is clicked, rather than loading immediately upon refreshing the page. The desired behavior includes activating the function on the initial click and then ...

Guide to creating and downloading a text file with Meteor

Is there a simple way to create a text file in Meteor on the server side and download it as a .txt file? // Server Side if (Meteor.isServer) { Meteor.methods({ 'scan-db': function () { // Scanning the database for corrupted data ...

What is the most effective way to structure JSON data for an API in Go using a struct?

As a newcomer to Go, I am exploring ways to simplify the normalization of JSON data received from the front-end (JS) to my API. To ensure that I correctly handle types when creating a variable from my model.Expense struct, I currently dump the payload into ...

Trouble with AJAX request in chrome extension

Currently, I am working on a task that involves retrieving the number of images from a specific directory on my server. To accomplish this, I have implemented PHP to determine the count of images and AJAX within my Chrome extension to fetch the number of i ...

Using nested ng-repeat to display <tr> and <td> elements

I am struggling with formatting my JSON data in a table layout. Here is an example of the structure: { "results": [ { "Header": "header1", "Sections": [ { "Name": "sec1" }, { "Name": "sec2" ...

What is the correct way to securely send the username and password from a ReactJS frontend to the backend for authentication?

My React application includes an onChange function on a form that collects username and password. Upon submission, the username and password are sent to the server side using redux dispatch in Node.js. On the server side, I am authenticating the credentia ...

What are the best strategies for enhancing the performance of the jQuery tag:contains() selector

My goal is to extract all elements from a webpage that contain a specific set of words. For example, if I have an array of random words: words = ["sky", "element", "dry", "smooth", "java", "running", "illness", "lake", "soothing", "cardio", "gymnastic"] ...

The presence of a check mark in the checkbox is constant, even when the attribute is missing

I am encountering an issue with my code where, upon clicking on my checkbox, the state is set to false but the check mark still remains visible when it shouldn't be present. Here is my code: <template> <div id="demo"> <f ...

using a JSON object as a parameter in a JavaScript function

I am trying to pass specific elements from a JSON object as arguments in a JavaScript function. Here is the script I am using: if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp1=new XMLHttpRequest(); } else {// code ...

Columns that can be resized in a right-to-left (

Whenever I use RTL, the columns behave erratically when resizing... I have implemented colResizable. You can see an example here: http://jsfiddle.net/r0rfrhb7/ $("#nonFixedSample").colResizable({ fixed: false, liveDrag: true, gripInnerHtml: "<d ...

Update the color of a form input using jQuery when the value has been modified

I need to modify the font color of a jQuery UI Select when the value is edited. The structure of the DOM is like this: <dd> <select class="filter large" name="xx" style="display: none;"> <option value="0">--</option> ...

Steps for assigning a texture to a child Mesh within an Object3D

My Object3D was imported in the following manner: var customObject; // defining a global object var loader = new THREE.ObjectLoader(); loader.load('path/to/object3d.json', function(object) { customObject = object; scene.add(customObject ...

Exploring various queries in Firestore

Does anyone know if there is a way to create a sentence similar to this one: return this.db.collection('places', ref => ref.where("CodPais", "<>", pais)).valueChanges(); I have tried using != and <> but neither seem to be valid. ...

Get the characters from a JavaScript string, but make sure to exclude

There is a text string that I need to work with: TEST:ABCDEGF:18:32 This text includes letters and numbers, but I want to extract all of them excluding the : character. Previously, I was using the following code successfully: lines.split(":"); However ...