Is there a way to retrieve the field names from a JSON array within a for loop?

Here is the structure of my Json array:

var data =
{
    "categories": 
    {
        "category1": 
        {
            "Name": "Maps",
             "Id": 3,
             "orderInList": 1
        },
        "category2": 
        {
            "Name": "Books",
            "Id": 2,
            "orderInList": 2
        }
    }
};

When I log the 'data' object to the console, the keys are displayed like this:

|         key           |    value  |

categories[category1][Id]     "3"

I am looking for a way to loop through this data in a for loop (without relying on JQuery's $.each) in order to distinguish between Name, Id, and orderInList pairs. Any suggestions on how to achieve this?

Check out this Jsfiddle example

Answer №1

Here is an example of how you can achieve this:

for (let category in data['categories']) {
    for (let key in data['categories'][category]) {
        let value = data['categories'][category][key];

        // Perform actions based on the key...
        switch (key) {
           case 'Name':
              // Do something
              break;
           default:
              break;
        }
    }
}

In this code snippet, the inner loop will have access to the key and value of the nested object, while the category variable holds the current category.

It's important to note that in JavaScript, object properties can be accessed using array-like syntax.

For instance, consider the following lines of code:

let some_object = {
    a: 0
};

// Both lines below achieve the same result, despite some_object not being an array.
some_object.a = 1;
some_object['a'] = 1;

Answer №2

The categories object within your main data object is structured with various child objects. By utilizing a for...in loop, you can effectively iterate through these child objects.

for (var category in data.categories) {
    // You have access to properties like `category.Name`, `.Id`, and `.orderInList`
}

Answer №3

Take a look at this

var information = {
  "categories": {
    "category1": {
        "Name": "Maps",
        "Id": 3,
        "orderInList": 1
    },
    "category2": {
        "Name": "Books",
        "Id": 2,
        "orderInList": 2
    }
  }
};

function representData(obj) {
  var representations = [];
  for (var k in obj) {

    if(!obj.hasOwnProperty(k)) continue;
    if (obj[k] instanceof Object) {
        var result = representData(obj[k]);
        for (var i = 0; i < result.length; i++) {
            representations.push("[" + k + "]" + result[i]);
        }
    }
    else {
        representations.push("[" + k + "] = " + obj[k]);
    }
  }
  return representations;
}

console.log(representData(information));
//output

["[categories][category1][Name] = Maps",
 "[categories][category1][Id] = 3",
 "[categories][category1][orderInList] = 1",
 "[categories][category2][Name] = Books",
 "[categories][category2][Id] = 2",
 "[categories][category2][orderInList] = 2"]

Identify the key, value pairs that correspond to Names, Id's, or orderInList's?

I suggest adding code to check if the key matches Names, Id, or orderInList as part of the recursion termination condition.

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

Header stabilization on scroll

On my webpage, I have a table header positioned in the middle of the page. However, due to the length of the page, I am looking for a way to make the header stay fixed at the top of the browser as the user scrolls down. My query is: Is there a method to k ...

Ways to adjust various json files

I'm facing a task where I have a directory containing 100 json files, and my goal is to insert [ at the start and ] at the end of each file. The current structure of the files is as follows: { item } But what I need to achieve is this format: [{ i ...

Implement jQuery to dynamically assign an "Active" class to tab elements based on the current page being loaded

INQUIRIES I have include: How do I apply a class to an element using jQuery, or any other method, for the active tab? Ensure that the dropdown tab appearing is the one containing the active tab, not always the Company one. In essence, I want the ac ...

Converting nested JSON structures into a PySpark DataFrame

Looking for a simple way to convert the provided JSON sample into a PySpark dataframe? Input : { "user": { "1": { "name": "Joe", "age": 28 }, "2" :{ "name": "Chr ...

Simple steps for Mocking an API call (Get Todos) using ComponentDidMount in React with Typescript, Jest, and Enzyme

About the application This application serves as a basic To Do List. It retrieves tasks from an API located at https://jsonplaceholder.typicode.com/todos?&_limit=5. Objective of the project The main goal is to test an API call that triggers ...

MongoDB was successfully updated, however the changes are not being displayed on the redirected

I have implemented the delete action in Node/Express as a web framework, where it is structured within a higher-level route: .delete((req, res) => { db.collection('collection-name').findOneAndDelete({ topic_title: req.body.topic_title}, ...

My jQuery code is encountering issues with the .each loop functionality

I have encountered an issue with the code snippet below, which is intended to hide the "IN STOCK" phrase on specific vendors' product pages. Upon testing, I noticed that the loop doesn't seem to be executing as expected when using console.log. Ca ...

Calculating the position of an element in an array passed from a separate file with ReactJS and Ant Design

I'm currently working with a file that contains some JavaScript code featuring an array with multiple objects containing key-value pairs. In my main file (App.jsx), I initialize a State Variable and assign it the array from another JS file. My goal no ...

The key property is present on the list item, yet the key warning persists

I have encountered various issues with this problem, but I am unable to pinpoint the exact cause. I am not extracting individual list items and simply displaying a UL with unique keys assigned to each item. However, when I log the results, I see something ...

Redirecting CORS in Cordova: A Comprehensive Guide

My Cordova/Phonegap app is encountering an issue while trying to retrieve certain files using AJAX. The specific error message that I receive states: XMLHttpRequest cannot load https://docs.google.com/uc?export=open&id=.... Redirect from 'https ...

having difficulty choosing a particular identifier from a JSON string

I'm currently working on a project to create an admin page for managing client information. However, I've encountered an issue where I am unable to select the client's unique ID to display all of their information on a separate page. On the ...

Alerting old session data following an AJAX request

After making an AJAX call that updates a $_SESSION variable, my <script> is supposed to echo out the new variable. However, it keeps alerting the old data even though the data is reaching the .php page and being stored in the session. I've attem ...

SequelizeDatabaseError: The operation could not be executed as there is no operator that allows for

I am attempting to create a join between two tables using UUIDs (also have IDs), and the relationships between these tables are quite complex... However, I encounter an error when running the query. The first table is named users, with its UUID labeled a ...

Exploring the keyof operator in Typescript for object types

Is there a way to extract keys of type A and transfer them to type B? Even though I anticipate type B to be "x", it seems to also include "undefined". Why does the keyof operator incorporate undefined in the resulting type? It's perplexing. I kn ...

Sending an Ajax request to a nearby address

I'm feeling a bit lost on how to achieve this task. I've been searching online, but it seems like my search terms may not have been quite right. My goal is to set up a RESTful api. $.ajax({ type: "POST", url: "https//my.url/", data: ...

Combining the powers of Nextjs and Vue

Currently utilizing Vue.js, I am now looking to leverage the Next.js framework for its SEO capabilities, server-side rendering features, and other advantages. While I do have some experience with React, my primary focus is on mastering Vue.js. Is it poss ...

Creating a number of arrays based on the row of a .CSV file can be accomplished in Angular by utilizing the

Implementing an Angular template to read .CSV files and generate a table involves creating two separate files: one for the header and another for the table content. For the header CSV file: header.csv https://i.stack.imgur.com/ojMo6.png For the table da ...

The method this.$el.querySelector does not exist

The data retrieved from the database is inserted into the input fields and submitted as a form. This data is an object that passes the value to the database. However, when I trigger this form, an error occurs. See example of the error <input id=" ...

Exploring the React Hook lifecycle methods of componentWillReceiveProps and componentDidUpdate

I am facing two main challenges: Despite the React guideline discouraging the use of derived state, there are still certain edge cases where it is necessary. In the context of a functional component with React Hook, what would be the equivalent implemen ...

Error: The specified schema for the model "superheroes" is missing and has not been registered. Please ensure the schema is properly defined and registered

After updating my server with nodemon, I encountered the following error: C:\Users\mikae\Desktop\Project\node-express-swig-mongo\node_modules\mongoose\lib\index.js:523 throw new mongoose.Error.MissingSchem ...