Is there a way to iterate through this (JSON) data in a loop

{

    "fulltime": [

        {"name": "oscar godson", "age": "20", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f29d81919380959d96819d9cb29a9b819f939b9edc919d9f">[email protected]</a>"},

        {"name": "daniel erickson", "age": "25", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1175707f78747d51666370786579657472793f727e7c">[email protected]</a>"},

        {"name": "john doe", "age": "18", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="22484d4a4c0c464d47624f5b414d4f52434c5b0c414d4f">[email protected]</a>"}

    ],

    "parttime":[

        {"name": "bill johnson", "age": "35", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b6d4dfdadadcd9ded8c5d9d8f6d1dbd7dfda98d5d9db">[email protected]</a>"}

    ]



}

With no prior knowledge of the values, such as fulltime being able to represent anything, I am seeking a function or method to iterate through all entries. Please refrain from using jQuery.

In addition, my goal is to retrieve the output of: all items within fulltime, all items within parttime, and so forth.

Answer №1

Iterating through the properties of your_object and logging each value:
for (key in your_object) {
    console.log(key + " category:");
    // Displaying items within the key
    for (var i = 0; i < your_object[key].length; i++) {
        console.log(your_object[key][i]);
    }
}

Answer №2

If you have the Firebug extension installed:

if(Firefox) {
  //"part-time", "full-time"
  console.log("Verifying employment status");
  for(var x = 0; x < info.length; x++){
    var employee = info[x];
    //Each individual
    for(var attr in employee) {
      console.log(attr + ": " + employee[attr]);
    }
  }
}

Note: Ensure that when iterating over an array, you use the proper method instead of for ... in .... Use

for(var i = 0; i < array.length; i++){...}
to iterate over arrays.

Answer №3

If you want to achieve this task, consider using a recursive function while being mindful of circular references. Check out the example provided below:

  var arr = [];

  /**
   * Convert Object to its string representation for debugging purposes
   * @param {Object} obj - The object to convert
   * @return {String} String representation of the object
   */
  var toObjectSource = function(obj)   {
     if(obj === null)   {
        return "[null]";
     }
     if(obj === undefined) {
        return "[undefined]";
     }

     var str = "[";
     var member = null;
     for(var each in obj)   {
        try   {
           member = obj[each];
           if(arr.indexOf(member) === -1) { // indexOf may not be supported in older JS versions
              arr.push(member);
              str += each + "=" + toObjectSource(member) + ", "; // Warning: potential recursive call
           }
        }catch(err) {
           alert(err);
        }
     }
     return str + "]";
  }

Be cautious about circular references as it can lead to "too much recursion" error. Here's an example that illustrates this issue:

 var obj = {
    "a": "a",
    "b": "b"
 }
 obj.c = obj;

Answer №4

To start off, it is recommended to validate your JSON data using a tool like .

If you have not yet converted your JSON string to an object, you can utilize the JSON.parse function available in web browsers or from http://www.json.org/js.html to accomplish this conversion.

When iterating through the properties of an object, consider using a "for in" loop with the following structure:

for (var name in myObject) {
    if (myObject.hasOwnProperty(name)) {
        // ....
    }
}

(refer to for more details). It's important to remember to declare the variable name as var name within the loop to prevent performance issues caused by global variables.

When looping through elements in an array, opt for a standard "for" loop over a "for in" loop for better efficiency. Additionally, improve performance by caching the length of the array in a local variable, especially if the property is accessed multiple times. For instance, instead of:

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

You should consider rewriting it as:

var arr = your_object[key];
var len = arr.length;
for (var i = 0; i < len; i++) {
   console.log(arr[i]);
}

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

Displaying JSON formatted dates using AngularJS

There is a JSON file with a "DataIscr" field structured like this: "DataIscr": "1969-6-17T00:00:00+01:00". A filter has been created for DataIscr: <label for="DataIscr">DataIscr:</label> <select style="width:200px" data-ng-options="Person.D ...

Create a filter for a table using select and jQuery

I've been working on a select filter to update a table, and while it works perfectly for one select element, I'm encountering an issue when trying to use multiple select elements simultaneously. Here is the code snippet (also available in this J ...

Issue with custom directive - bi-directional binding not functioning as expected

I'm currently working on creating a custom directive in Angular that transforms a tag into a toggle button, similar to a checkbox. As of now, the code I've developed updates the internal variable within isolated scope, but bidirectional binding ...

Creating dynamic connections between Plain Old Java Objects (POJOs) and RESTful APIs through automated

I have a POJO class that requires me to access a RESTful web service using specific properties from the POJO as parameters. The challenge lies in not knowing the endpoint and its parameters until runtime. Essentially, the user will set up the endpoint, i ...

Python function that generates multiple response outputs using the write method

Can anyone verify if the code below is valid in Python? It involves calling a server and returning the response in multiple ways. Instead of using nested "if" statements, I wanted to implement it like this: def get(self): self.response.header ...

What is the best way to trigger a 'Save As' dialog box on a browser when a button is activated within an Angular application, guaranteeing cross-browser compatibility?

The solution needs to be compatible with both Windows and Mac operating systems. Additionally, we should be able to specify a default file name and type. ...

Converting a JSON object to a JSON array can sometimes be challenging during JSON parsing

I'm attempting to convert a JSON String into an array by using the code snippet below: try { String holder = getJSONString(getApplicationContext()); JSONArray JSONARR= new JSONArray(holder); List<datatemp> dataList = new ArrayList& ...

Using WebRTC on a shared hosting environment (with SSH access) without the need for nodejs, ideally implemented in PHP

As I was exploring ways to integrate webRTC into a website that I am creating on shared hosting, I stumbled upon this GitHub repository by nielsbaloe. It has been incredibly helpful in establishing a basic connection. This particular code snippet appears ...

Transforming res.json() into an Array of Objects

I am dealing with a Java webservice that outputs a list of Json objects with specific properties: public class Oferta { private int id; private String categoria; private String descricao_oferta; private String anunciante; private double valor; private boo ...

transferring data from config file (conf.js) to a grunt task or sharing information between different grunt

Is there a way to transfer data between different grunt tasks? I need to send a value from one grunt task to another grunt task. In my case, I want to pass a value to a new grunt task after running a protractor test. I attempted to store the value in proc ...

Using a dynamic image URL from JSON to display it in a bitmap

I used the instructions provided here to print Sample Receipts. This is my JSON data: { "response": { "status": "http://www.neodynamic.com/articles/How-to-print-raw-ESC-POS-commands-from-PHP-directly-to-the-client-printer/php-print-esc-po ...

Guide to implementing nested asynchronous calls using a foreach loop

I am eager to enhance my skills and gain a better understanding of how to improve this code. While the current code is functioning, I suspect there may be an issue that needs addressing. Here's the concept: 1: Initially, I send the first HTTP request ...

update angular component after deleting an item

After deleting a contact in the table, I'm trying to refresh my contact list page but it's not working. Any suggestions? This is the list of contacts in the contact.component.ts file Swal.fire({ title: 'Do you want to delete this contac ...

JavaScript debugging causing system freeze

Currently, I am working on a project that involves using MVC and dropdown lists. My issue arises when the dropdown list changes, as there is some javascript code that needs to execute. To troubleshoot the problem of the system locking up every time I tried ...

Retrieve the header tag from API using Nuxt

I am trying to dynamically set OG:Tags using an API head() { this.$axios .get(`............`) .then((response) => { this.og_title = response.data.message.course.course_name; this.og_description = response.data.message.course.description; ...

Node.js: Leveraging Express to Compare URL Parameters and Handle Delete Requests with Array Values

Having some issues with the Express routes I set up for an array of objects and CRUD operations. Everything works smoothly except for the "Delete" operation. I am trying to delete an object by matching its URL parameter ID with the value of its key. Howev ...

When exporting a Mongoose model, it mysteriously becomes undefined

I am encountering an issue when trying to import the DemandeTransports model from a specific file: //@/components/database/model/Schema.js import { Schema } from "mongoose"; import mongoose from "mongoose"; const userSchema = new Schem ...

Every time the page is refreshed, ExpressJS and NodeJS are working together to duplicate the array

var express = require("express"); var router = express.Router(); const fs = require("fs"); const path = require("path"); const readline = require('readline'); const directoryPath = path.resolve(__dirname,"../log ...

Is the script failing to retrieve the innerHTML content?

Here is a snippet of HTML code: <div id="team_players"> <h3>Players</h3> <button class="bold-btn" onclick="teamAct('player_list');">Refresh List ↻</button> <table> <thead> <tr> ...

Update ng-Bootstrap ToDate field by removing the date when selecting a fromDate

Is there a way to clear the date from the toDate input field while selecting a date from the fromDate input field in ng-bootstrap? <form class="row row-cols-sm-auto" *ngIf="showDateRangeImp"> <div class="col-12" ...