Content retrieved from Ajax response

When making an ajax call and receiving JSON data (Data Attached), the data appears as follows after being converted to a String:

{
   "shipments":[
      {
         "companyName":"TriStar Inc.",
         "shipmentDate":null,
         "transMode":"NDAY",
         "paid":true,
         "delDate":null,
         "custRefInfo":{
            "customerName":"DAISY N.",
            "customerZip":"90544"
         },
         "orderStatus":true
      },
      {
         "companyName":"Carbo Box",
         "shipmentDate":null,
         "transMode":"COUR",
         "paid":true,
         "delDate":null,
         "custRefInfo":{
            "customerName":"TOM K",
            "customerZip":"07410"
         },
         "orderStatus":true
      }
   ]
}

Viewing the JSON response in Firefox, it displays as:

[Object { companyName="TriStar Inc.", shipmentDate=null, transMode="NDAY", more...}, Object { companyName="Carbo Box", shipmentDate=null, transMode="COUR", more... } ]

The task at hand is to extract the companyName and customerName fields from this response. The current method being used is not effective:

 load: function(response){
        for(var i in response){
             console.log(response.shipments[i].companyName);
  }

Answer №1

When dealing with a string that is in JSON format, it is important to first parse it.

var data = JSON.parse(jsonString);

After parsing, you will have a valid object literal that can be accessed normally.

var items = data.items;

items is now an array in JavaScript...

for(var i = 0; i < items.length; i++){
    console.log(items[i].itemName);
}

It is worth mentioning that the for(var i in x) loop should not be used with arrays.

Answer №2

retrieve.shipments[i].companyName

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

Using PHP to loop through SQL data and convert it to JSON format, mapping information from two tables based on their related IDs

I always wish for your good health. I am currently facing an issue trying to generate a JSON array from 2 tables. Here are the tables I have: Table 1: app_produk_ready Table 2: app_produk_ready_img Below is the PHP code I have written: <?php require_ ...

Exploring the use of the caret symbol (^) for exponentiation

I am embarking on a project to develop an uncomplicated graphing calculator that enables users to input a function of f (such as f(x) = x^2+2x+6). Essentially, the JavaScript code should replace the x in the function with a specific number and then compute ...

Listening for changes in class property values in TypeScript with Angular involves using the `ngOnChanges`

Back in the days of AngularJS, we could easily listen for variable changes using $watch, $digest... but with the newer versions like Angular 5 and 6, this feature is no longer available. In the current version of Angular, handling variable changes has bec ...

Utilizing Backbone.js: Passing a variable from a route to a view, collection, or model

Currently working on a mobile website project where I have set up a directory named 'api' containing PHP files that retrieve JSON formatted data from a remote API to avoid cross-domain issues. However, one of the PHP files requires a GET paramet ...

Effortlessly initiate the consecutive playback on SoundCloud

I'm currently working on my music blog and I'm looking for some guidance in implementing a feature where the widgets start playing one after the other. Specifically, I have both SoundCloud and YouTube widgets, but I would like to focus on achievi ...

Iterate over a JSON array using jQuery

I am attempting to iterate through this data to extract the 'name' values. Here is my current code, but it does not seem to be functioning correctly. I have tried a few variations from suggestions here, but none of them have worked. $.get("/ ...

Ways to incorporate radio buttons, checkboxes, and select fields into a multi-step form using JavaScript

In the snippet below, I have created a multi-step form where users can provide details. The issue is that currently only text input fields are being accepted. The array of questions specifies the type of input required for each question: Question no.1 req ...

Retrieve various URLs within an object using React

My task involves extracting all URLs from a specific object. Object { "Info": "/api/2", "Logo": "/api/2/Logo", "Photo": "/api/2/photo", } I aim to store the responses in a state, ensuring t ...

Press on the row using jQuery

Instead of using link-button in grid-view to display a popup, I modified the code so that when a user clicks on a row, the popup appears. However, after making this change, nothing happens when I click on a row. Any solutions? $(function () { $('[ ...

What is the best way to display JSON data using a Horizontal scroll view and POST method?

I encountered an issue while trying to display my JSON data in a horizontal view instead of a list view. Although there are no errors being shown, the data is not being displayed as expected. However, I can see the data in the console. Initially, I create ...

Utilizing Java to extract JSON path values and assign them to variables

I'm facing an issue with my code for parsing a JSON string into an object. Previously, I had the following code: public AgentStrategy parseJsonToObject(String jsonString) { Gson gson = new Gson(); AgentStrategy agent = gson.fromJson(jsonString ...

Add .json files to your database

After successfully downloading tweets into a json file, the next step is to import it into a database using the following function: def import_json(fi): logging.warning("Loading tweets from json file {0}".format(fi)) for line in open(fi, "rb"): data ...

How can you integrate jquery ajax in WordPress?

Recently, I started learning about jquery and have been following a tutorial on creating instant search using jquery. The tutorial can be found here. Now, I am trying to implement this on my WordPress site, but it seems like things work differently when d ...

Utilizing a jQuery AJAX request to invoke a web method within a

My goal is to integrate jQuery mobile into an existing ASP.NET webform application. I am currently considering using pure HTML controls to create the jQuery Mobile page. I am aware that when making an AJAX call, I can access code-behind static web methods, ...

Unable to load dynamic data in Angular 2 smart table

Currently, I am utilizing Angular 6 along with smart table by visiting this link: . Everything was functioning smoothly, until the moment I attempted to switch from static to dynamic data: The following code works perfectly and displays all the content ...

What is the process for activating a button after a checkbox has been selected? Additionally, how can a value be dynamically transferred from a checkbox to the rezBlock_1 block?

What could be the reason for my code not functioning properly? How can I enable a button once a checkbox is selected? Also, is there a way to dynamically move text from a checkbox to the rezBlock_1 block? CODPEN https://codepen.io/RJDio/pen/RwPgaaZ doc ...

Is it possible for Node.js to not automatically restart the server when modifying .js files?

Right now I have node-supervisor set up to detect changes in .js files, and while it works well, I've realized that it restarts the server every time a js file is saved. Is there a way to save a server-side .js file without triggering a server restart ...

I would like to deserialize a JSON object to retrieve a String that represents

Dart programming language is truly remarkable. However, I have encountered a potential issue with the JSON.parse function in Dart that seems to be creating integers in the Map object when the input is actually a string. This could lead to unwanted outcomes ...

The users in my system are definitely present, however, I am getting an error that

Whenever I attempt to retrieve all the post.user.name, an error is displayed stating Cannot read properties of undefined (reading 'name') I simply want to display all the users in my node Even though user is not null, when I write post.user, i ...

When using CKEditor, pressing the Enter key results in the insertion of <br /> tags

Whenever I use ckeditor, I find that pressing enter results in two <br /> tags being inserted. While I want to keep the line break tags, having them appear twice is not ideal. In my config.js file, I have set the configuration for the enter key as f ...