Parsing JSON data in JavaScript

I am facing an issue with parsing JSON using JavaScript. After the completion of the loop, my variable 'text' is not getting the expected result. Can someone please explain how I can correctly parse this JSON?

var xmlr = null;
var text = '';
if (window.XMLHttpRequest) {
    xmlr = new XMLHttpRequest();
} else {
    xmlr = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlr.onreadystatechange = function () {
    if (xmlr.readyState == 4 && xmlr.status == 200) {
        var data = JSON.parse(xmlr.responseText);
        for (var i = 0; i <= data.length; i++) {
            text += '<option>' + data[i].member_first_name + '</option>';
        }
        console.log(text); // here not get result in text
    }
}
xmlr.open("GET", "data.json", true);
xmlr.send();

The contents of data.json are as follows:

[
{"member_id":"3","member_first_name":"sachin ","member_last_name":"kumar"},
{"member_id":"4","member_first_name":"abhijit","member_last_name":"kumar"},
{"member_id":"5","member_first_name":"nithin","member_last_name":"ev"},
{"member_id":"6","member_first_name":"tukaram","member_last_name":"kumar"},
{"member_id":"7","member_first_name":"manish","member_last_name":"mungle"},
{"member_id":"8","member_first_name":"dsfdgfh","member_last_name":"dfgfhgfh"},
{"member_id":"9","member_first_name":"hjhgjkhkhj","member_last_name":""},
{"member_id":"10","member_first_name":"hjhkjhggf","member_last_name":""},
{"member_id":"11","member_first_name":"klkjlgfhf","member_last_name":"hjghkj"},
{"member_id":"12","member_first_name":"jkhkjhkl","member_last_name":"hgjgffhfkhj"},
{"member_id":"13","member_first_name":"hfgtjgjhg","member_last_name":"fghjgfhjg"},
{"member_id":"14","member_first_name":"hgjgfjhj","member_last_name":"hgjhgjhfg"},
{"member_id":"15","member_first_name":"cvcxvnvnbv","member_last_name":"nbvcbvc"},
{"member_id":"16","member_first_name":"vbvcnbnbm","member_last_name":"vbxgdssdg"},
{"member_id":"17","member_first_name":"lkfndbfbsd","member_last_name":"dfggfhfh"},
{"member_id":"18","member_first_name":"fghjjdfd","member_last_name":"fgfghghf"},
{"member_id":"19","member_first_name":"ghgfjhfj","member_last_name":"fghfhfd"},
{"member_id":"20","member_first_name":"dfhgfhh","member_last_name":"gdfhfd"}
]

Answer №1

A great way to navigate through the object array efficiently in JavaScript is by utilizing the for/in loop instead of a traditional for loop. Check out this sample code that demonstrates how to traverse an object array:

var xhr = null;
var output = '';
if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
} else {
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
        var jsonData = JSON.parse(xhr.responseText);
        for (var prop in jsonData) {
            output += '<option>' + jsonData[prop].member_first_name + '</option>';
        }
        console.log(output); 
    }
}
xhr.open("GET", "data.json", true);
xhr.send();

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

Utilizing ng-options to pass values rather than entire objects

Currently, I am parsing a .json file and displaying all available options in a select dropdown menu: <div bo-switch-when="dropdown"> <fieldset> <select ng-options="options.text for option in question.body.options" ng-model="question ...

Find the variance between two arbitrary JSON strings and provide the contrast in map form

Is there a way in Java to compare 2 random JSON strings and retrieve the variance between them? I am looking for a solution that can detect differences even if the order of the JSON objects is not consistent. ...

An error occurred while attempting implicit conversion using "as" from JsLookupResult to a List of Maps containing String keys and Js

In my scala script, I am trying to extract the notifiers object from the parsed jsonValue. object App { def main(args: Array[String]) { val json = """{ "notifiers":[ { "type":"url", "attribut ...

Encountering issues while establishing a connection to SQL Server through Node.js

I've developed a Node.js application to interact with SQL Server. Here's the code snippet: app.get('/SalesStatistics', function (req, res) { var Connection = require('tedious').Connection; // configuration for the databas ...

Mistake found in translating C# to VB .NET with the help of newton.jsoft (json.net) in Visual Studio 2012

Can you spot the issue in this code snippet when attempting to translate C# into VB .Net using Newton.Jsoft (JSON.Net) in Visual Studio 2012? public static List<TradeInfo> GetTrades(BtcePair pair) { string queryStr = string.Format("https://btc- ...

Returning a 404 Error stating "Invalid request to /api/users/register."

Encountering an issue with proxy connection - unable to determine the root cause despite verifying all routes. Not able to successfully register the user and store data in MongoDB. Seeking suggestions for resolution. Thank you. Attempting to send user reg ...

Utilizing the nativescript-loading-indicator in a Vue Native application: Step-by-step guide

I am attempting to incorporate the nstudio/nativescript-loading-indicator package into my Vue Native App, but I am experiencing issues with its functionality. import {LoadingIndicator, Mode, OptionsCommon} from '@nstudio/nativescript-loading-indicato ...

What should I do to resolve the error message TypeError: _components_firebase_Firebase__WEBPACK_IMPORTED_MODULE_2__.default.auth is not a valid function?

I have implemented Firebase with next.js and organized my files as shown below. However, I am encountering an issue with using the firebase client side SDK during the sign-up process. Firebase.js is where the firebase app is initialized import firebase fr ...

Using Angular function to retrieve Firebase snapshot

Trying to access a user's profile image stored in Firebase at /user/[uid]/info/photoURL This is being done using Angular functions. Here is the code snippet: HTML: <img ng-src="{{getImg(user.uid)}}" alt=""> Javascript: $scope.getImg = func ...

There is no 'Access-Control-Allow-Origin' header found on the requested resource in Heroku for Node.js

Here is the header setup in my Node.js API app: res.header("Access-Control-Allow-Origin", "*"); res.header( "Access-Control-Allow-Headers", "Origin, X-Requested, Content-Type, Accept Authorization" ); ...

Leveraging Vue properties within CSS styling

I am looking to utilize Vue data/prop variables within the <style> tag located at the bottom of my component. For example, suppose I have a component structured like this: <template> <div class="cl"></div> </template> < ...

Utilizing Bootstrap's Multi-Grid System

I am currently working on implementing a Bootstrap grid design that resembles pic1.jpg. However, I am facing challenges in achieving the desired layout, as pic2.jpg shows the current scenario. Below, I have shared the code I am using. pic1.jpg :- ! pic2. ...

Error: Unable to access attributes of an undefined object (specifically 'headers') in the Next.js evaluation

I encountered an issue with next js TypeError: Cannot read properties of undefined (reading 'headers') at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:254:61) Snippet of the pro ...

Adjust google maps to fill the entire vertical space available

I found this helpful resource for integrating Google Maps into my Ionic app. Everything is working smoothly, but I am trying to make the map fill the remaining height below the header. Currently, I can only set a fixed height in pixels like this: .angula ...

What is the best way to arrange an array of objects based on a specific attribute?

Ordering object based on value: test": [{ "order_number": 3, }, { "order_number": 1, }] Is there a way to arrange this so that the object with order_number 1 appears first in the array? ...

Accessing ExpressJS from AngularJS through local server

My latest project involves building a Web Application using AngularJS and ExpressJS. In this application, I have set up a GET "/" route in my app.js file to render the index.html page when accessed. One interesting feature is the GET "/test-data" route in ...

What is the appropriate method to call a function when a parameter is unnecessary?

Just to confirm, is this the correct way to call a function when a parameter is not needed? function load_img(src, alt, el, other_src) { // check if other_src exists, not null, defined, not empty, etc... } //call the function load_img(src, alt, '# ...

Using a render target causes certain elements of my visual graphics to become hidden

Hey there, I've been experimenting with render targets lately and encountered some issues. I've put together a simplified example below: init = function() { // RENDERER canvas = document.getElementById("mycanvas"); renderer = new THREE ...

Tips for preserving a collection of items in a thesaurus?

My project involves a Python 3.5 program that manages an inventory of various objects. One key aspect is the creation of a class called Trampoline, each with specific attributes such as color, size, and spring type. I frequently create new instances of thi ...

Module request: How can I save the gathered cookies as a variable?

library: https://www.npmjs.com/package/request I am attempting to simultaneously log in with multiple accounts on a website. To manage each session effectively, I plan to create an object where I will store the cookies associated with each account. Now, ...