What is the best way to loop through a JSON file using JavaScript?

Having an issue here. I need to loop through the attributes of a JSON structure, like the one shown below:

var txt = '{"employees":{' +
'"p1":{'+
    '"info":{'+
        '"firstName":"John","lastName":"Doe" }},' +
'"p2":{'+
    '"info":{'+
        '"firstName":"Anna","lastName":"Smith" }},' +
'"p3":{'+
    '"info":{'+
        '"firstName":"Peter","lastName":"Jones" }}'+

'}}';

I'm looking for a way to achieve this without using specific p values like p1, p2, p3 in my code.

json.employees.p1.info.firstName;

This is not the approach I want to take. Instead, I'm aiming for something similar to this:

for(var i = 0; i<3;++i){
    console.log(json.employees.p[i].info.firstName);
}

Any ideas on how to accomplish this?

The reason behind this requirement is that the attribute p can be any number (N), so hardcoding p1, p2, p3, etc., isn't feasible.

Answer №1

To retrieve information from JavaScript objects, you can utilize the bracket notation. This method is particularly handy when you need to use a variable or expression as the property name.

In your specific case, you can access the data stored in the employees object like so:

json.employees['p_'+(i+1)].details.lastName

Answer №2

A method to go through objects involves iteration:

for (var key in the_object)
    console.log(the_object[key]);

In this situation, to loop over all P objects:

for (var key in json.pets)
    console.log(json.pets[key]);

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

Moving items in a leftward direction

I am trying to create a CSS animation that makes multiple objects slide from right to left. The height of these objects should be random and the speed of the animation should also vary randomly. While I have successfully achieved this using JavaScript, I a ...

What is the most effective way to display multiple variables simultaneously in Mongoose/Node.js?

As a newcomer to programming, my initial major project involves building a website using Mongoose and Node.js. I have a query regarding rendering two variables for ejs simultaneously without encountering an error due to attempting to render a query that h ...

Converting a JavaScript array to formData

Struggling with sending an array via Ajax to PHP. For more information, visit jsfiddle https://jsfiddle.net/CraigDavison/9spyn7ah/ function autoPopulate() { var cast = "John Wayne, Julia Roberts, Kevin Spacey"; cast = cast.split(', '); ...

Creating a function to manipulate an element on a different webpage

Upon clicking a button on Page1, a function is triggered which then calls another function to generate HTML and append it to a div with the #lista id. The issue here is that #lista belongs to Page2, so I am unsure if there is a syntax similar to ajax where ...

The jQuery library triggers an error that can only be resolved by refreshing the

I am currently experiencing an issue with my form (form links are provided below, specifically referring to form1). The problem arises when I include jquery.js, as it fails to load the doAjax and getIP functions that are contained in a separate js file nam ...

Laravel's routing system may cause complications when trying to send data via jQuery AJAX post requests

My current challenge involves passing an ID to a PHP script through AJAX. Previously, everything was working perfectly with the code snippet below: var baseURL = '/W4W/public/'; function voteUp(){ var snippetID = document.getElementById(&ap ...

How can I display all categories in a Radar chart using amcharts 5

I'm currently using React with amcharts to generate a Radar chart. The data I have is structured as an array of objects like this: { category: 'Something', value: 5 }. There are a total of 12 items in the data set. However, when plotting t ...

Steps to redirect to an external page after successful login, even if it's not hosted on the server

I have developed an HTML5 app on my phone. Once the correct username and password are entered, the app is supposed to connect to an external server, authenticate the credentials in the database, and then redirect me to another page (Home Page) within the a ...

Creating a persistent toolbar in Vuetify: Tips and tricks

Within my Vuetify app, I've implemented a toolbar: <v-toolbar dark color="primary"> <v-toolbar-side-icon @click.stop="drawer.drawer = !drawer.drawer"></v-toolbar-side-icon> <v-toolbar-title>{{drawer.title}}</v-toolb ...

Is there a way to embed an AJAX submit form into a notification without the need for page refresh?

I have integrated the jQuery plugin toastr js () for notifications on my website. I am facing an issue where I want to include a contact form within the notification popup and submit it using AJAX. Despite having the form working fine outside of the toastr ...

Struggling with organizing ul list elements in alphabetical order (either from A to Z or Z to A) using React.js

I am completely new to using React, so please bear with me if this sounds like a silly question. I've been trying to figure out why my sortList function isn't functioning properly. Below is the initial part of my component code: class NewApp ext ...

Remove any words that are not included in the specified list

Here is the code snippet to achieve the desired functionality: const { words } = require("../../json/words.json") const args = message.content.split(' ') const wordss = words.filter(m=> m.includes(args)) if(args > 1 || !wordss) { ...

The unit tests are passing successfully

Trying to create unit test cases for a web API call. This one showcases success: Success Unit Test (jsfiddle) getProduct("jsonp","https://maps.googleapis.com/maps/api/e Here is an example of an error, but the test result still shows "pass": Error ...

Basic illustration of AJAX web-app, encompassing client and server components

Currently, I am immersing myself in the world of AJAX by tapping into online resources and delving into some informative books. While doing so, I discovered that AJAX is not exactly a groundbreaking technology in and of itself, but rather a method of lever ...

Another drop-down is hiding the bootstrap-select drop-down from view

What could be causing some parts of the first drop-down menu to be hidden by another drop-down menu below in the code snippet provided? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv= ...

yii2: Gridview selected rows processing issue - ajax post data missing

Within my yii2 application, I am looking to group machines into specific machine groups. Due to the large number of machines, users must select them via a checkbox column in a kartik-gridview, which offers sorting and filtering capabilities that a standard ...

Having trouble retrieving an object through a GET request in Node.js with Express

Currently, I am going through a tutorial on Node.js by Traversy Media and I have encountered an issue that has me stumped. The problem arises when I attempt to retrieve the response of a single object from an array of objects using the following code: app ...

Do back-end routes get activated when the route path in the URL matches, or when a fetch request is initiated from the front-end?

Exploring the contrast between utilizing a fetch API versus directly visiting the URL corresponding to the route path. Consider a backend route structured as follows: let ALL_RESTAURANTS = [ { id: "0b65fe74-03a9-4b37-ab09-1c8d23189273", name: ...

Array of JSON objects

My current code seems to be generating an unexpected data structure. Here's what I'm doing: I receive a value from an input field (request.body.id) in JSON format, which I then parse and push into an array along with another object (data). This p ...

How to Make an Element Fade Out After Adding a Class in JQuery

I'm struggling with fading out an image after applying a tilt class to it. The transition doesn't seem to work properly and the image just disappears without the expected animation. The class I'm trying to add simply tilts the image 90 degr ...