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

Capturing the Facebook Login Event to dynamically modify the content of the main webpage

My current project involves creating a Facebook-based login system using JavaScript. When a user clicks a button, I want one div to be replaced by another if the user is already logged in to Facebook. If they are not logged in, I prompt them to enter their ...

What is the best way to execute a code once another has successfully completed its run?

Within milliseconds, I am required to update a JSON file with new data and then fetch that updated information. However, after posting the data into the JSON file, it appears that when attempting to retrieve it, the old data is returned instead of the newl ...

Having trouble with CSS transitions in a Next.js or Tailwind application?

"use client"; import React, { useState } from "react"; import Image from "next/image"; import Link from "next/link"; const NavigationBar = () => ( <div id="navbar"> <Link href="/">Home</Link> <Link href="/about">About& ...

What is the best way to target an HTML attribute using jQuery?

I have customized a Textbox by adding a special attribute: <asp.TextBox MyCustomAttribute="SomeValue"><asp.TextBox> Now, I want to retrieve this value from within an AJAX success function. Please note that I have excluded irrelevant attribut ...

When using jQuery AJAX to Like/Dislike, a 500 (Internal Server Error) is returned, but the functionality works correctly upon reloading the

My website has a feature where users can press a Like Status button that uses AJAX to send data to the controller. When the button is clicked, it changes from "like" to "dislike" and all associated classes and form actions are updated accordingly. The is ...

Trouble with the filter function in the component array

I am facing an issue with creating and deleting multiple components. I have successfully created the components, but for some reason, I am unable to delete them when I click on the "delete" button. state = { data: '', todoCard: [], id ...

Rapidly update code changes using the development mode in Next.js with the VS Code Remote Container/devcontainer

Struggling to enable Next.js' Fast Refresh feature while using a VS Code Remote Container. Running npm run dev displays the app on localhost, indicating the container functions properly - but Fast Refresh remains ineffective. Next.js version: v11.0.1 ...

Vue.js - encountering an issue with undefined response data

Greetings! I've encountered a script issue while trying to submit a form in VUE. The error message displayed in the developer panel states: "TypeError: error.response.data.errors is undefined". As a newcomer to Vue, I'm seeking some assistance as ...

Using Vue.js to update content in input files

I have a Vue.js template file that includes data containing various documents. Within the page, there is a table with rows that feature upload file input buttons, structured like this: <tr v-for="(doc, index) in documents"> <td :id="'doc-& ...

Why does the combination of "minus, space, minus" result in the "plus" operation?

When running the command 'node -e 'console.log(- -1)' it outputs 1, which is expected. However: When executing the command 'node -e 'console.log(1 - - 1)' it displays 2, which puzzles me. It seems like when subtracting a ne ...

Tips for integrating JavaScript libraries with TypeScript

I'm looking to add the 'react-keydown' module to my project, but I'm having trouble finding typings for it. Can someone guide me on how to integrate this module into my TypeScript project? ...

Enhancing Typography in Material UI with Custom Breakpoints in React CustomThemes

Currently, I am utilizing material UI and React to develop a single-page application (SPA). However, I have encountered an issue with ensuring that my pages are responsive for smaller screen sizes. To address this, I have been manually adding fontSize: { x ...

Issues arise when utilizing external scripts alongside <Link> components in ReactJS, resulting in them becoming unresponsive

I'm experiencing some difficulties with an external script when using <Link to="/">. The script is included in the main layout file index.js as componentDidMount () { const tripadvisorLeft = document.createElement("script"); tripadvisorLef ...

Is it possible to target an iframe and display text simultaneously?

Trying to create a unique menu that interacts with an iframe and displays text in a separate div upon clicking. Example: • Menu item 1 clicked. • "https://wikipedia.org" loads in the iframe. • Address of the wikipedia page displayed in a diffe ...

Choosing various li classes within a navigation bar

Struggling to pick the right JQuery elements for my portfolio site. The aim is to show/hide the .inner (Task) items by clicking on the .outer (Category) items, complete with rotating .arrows when the menu expands. Check out a similar question, along with ...

Unable to attach an event listener to an element fetched from an API

I'm currently in the process of developing a trivia web application using an API, and my goal is to incorporate an event listener onto the button which corresponds to the correct answer. This way, when users click on it, a message will appear confirmi ...

Having difficulty communicating with the smart contract using JavaScript in order to retrieve the user's address and the balance of the smart contract

Hi there, I am a newcomer to the world of blockchain technology. Recently, I created a smart contract designed to display both the contract balance and user data, including the address and balance of the user. The smart contract allows users to deposit fun ...

Information regarding the PointField within the rest_framework_gis module

Currently, I am developing a web application that utilizes rest_framework_gis. One of the models in my project includes a PointField. from django.contrib.gis.db import models from django.contrib.auth import get_user_model User = get_user_model() class ...

What is the best way to locate a function (whether it be a GET, POST, etc.) within index.js using an Express router

I've been trying to set up a router in Express, following a tutorial. However, my code can't seem to find the function get/users. Interestingly, it works fine when I include it in index.js index.js : const express = require('express' ...

Currently I am developing a Minimax Algorithm implementation for my reversi game using react.js, however I am encountering a RangeError

I've been implementing a Minimax Algorithm for my reversi game to create a strong AI opponent for players. However, I ran into the following error message: "RangeError: Maximum call stack size exceeded" How can I go about resolving this issue? Here ...