Navigating through object arrays using a loop

I have multiple arrays within an object that I would like to iterate through using numeric values. This is necessary in order to assign them to different slots in an accordion loop. The JSON file containing the data looks similar to this (Pokemon used as an example):

{
  "Pokemon": {
    "FirePokemon": [
      {
        "name": "Vulpix",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      },
      {
        "name": "Charmander",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      }
    ],
    "WaterPokemon": [
      {
        "name": "Squirtle",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      },
      {
        "name": "Wartortle",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      }
    ],
    "GrassPokemon": [
      {
        "name": "Bulbasaur",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      },
      {
        "name": "Oddish",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      }
    ]
  }
}

The objective is to reference the data as follows:

function SetJsonDataToAccordion() {
    for (var i = 0; i < Object.keys(pokemondata).length; i++) {
        CreateAccordionContent(pokemondata[i], ".accordtitle"+i);
    }
}

In this case, pokemondata represents the variable containing all the JSON data. While pokemondata[i] doesn't function correctly, the goal is to cycle through the various types of Pokemon in the loop without explicitly naming the arrays. It works when directly specifying a specific array like 'pokemondata.FirePokemon', but the requirement is to iterate through them. Is there a method to achieve this by iterating through the arrays within an object?

Answer №1

To iterate through the nested objects, you can utilize a combination of for and in loops.

In this scenario with your provided example, you will require 3 levels of nested loops to access all the data.

var obj = {
  "Pokemon": {
    "FirePokemon": [{
        "name": "Vulpix",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      },
      {
        "name": "Charmander",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      }
    ],
    "WaterPokemon": [{
        "name": "Squirtle",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      },
      {
        "name": "Wartortle",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      }
    ],
    "GrassPokemon": [{
        "name": "Bulbasaur",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      },
      {
        "name": "Oddish",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      }
    ]
  }
};

for (var key1 in obj.Pokemon) {
  console.log("=======================");
  console.log(key1);
  console.log("=======================");

  for (var key2 in obj.Pokemon[key1]) {
    for (var key3 in obj.Pokemon[key1][key2]) {
      console.log(key3 + ": " + obj.Pokemon[key1][key2][key3]);
    }
    console.log("****");
  }
}

Answer №2

To iterate through both, utilize Object.keys to fetch the pokemon types list. This data can then be used to loop through each individual pokemon.

let pokeData = obj.pokemonData;
Object.keys(pokeData).forEach(type => {
   // perform an action with pokemon type
   pokeData[type].forEach(pokemon => {
      //execute a function with actual pokemon data
   });
});

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

The modal window obstructs my view on the screen

You are working with a modal form that triggers a POST method in your controller https://i.sstatic.net/0vbOy.png Here is the view code: <div class="modal fade" id="agregarProducto"> <div class="modal-dialog" role="document"> < ...

I am looking to superimpose one rectangle over another rectangle

I am looking to create something similar using CSS and TypeScript/JavaScript: Could someone please guide me on how to achieve this? My attempt with a flex container looks like this: I am new to front-end development. Can anyone point out what I might be ...

When trying to implement appDir and withPWA in next.config.js, an error has been encountered

My next.config.js is set up with next-pwa and an experimental app feature included. const withPWA = require('next-pwa'); module.exports = withPWA({ pwa: { dest: 'public', disable: process.env.NODE_ENV === 'development&ap ...

Is there a way to dynamically adjust the height of a DIV block?

I have a situation where I need the height of one div to automatically adjust based on changes in the height of another div. var height = jQuery('#leftcol').height(); height += 20; jQuery('.rightcol-botbg').height(height); Unfortun ...

Transferring data from a stream in NodeJS to FrontEnd using ReactJS

How are you doing? I'm trying to figure out how to send a large data request from PostgreSQL to the FrontEnd in JSON format. Can anyone help with an example of how this can be achieved? Thank you. Here is my code: const express = require('expr ...

Having trouble with your Jquery resize or scroll function?

function adjustNavbar() { if ($(window).width() > 639) { $(document).scroll(function () { if ($(window).scrollTop() > 60) { $('.navbar').addClass('background', 250); } else { ...

React Native: error - unhandled action to navigate with payload detected by the navigator

Having trouble navigating from the login screen to the profile screen after email and password authentication. All other functions are working fine - I can retrieve and store the token from the auth API. However, when trying to navigate to the next screen, ...

Angular-Chart.js - Issue with Tooltip not displaying for data points with a value of 0

Within my Angular Chart JS Application, I have encountered an issue where having "0" values in my data array seems to affect the functionality of the tooltip for the corresponding bar. Interestingly, changing the "0" values to "0.1" resolves the problem... ...

Retrieve the thousand separator for numbers using Angular in various languages

When using the English locale, numbers appear as follows: 111,111,222.00, with a comma as the thousand separator and a point as the decimal separator. In languages like German, the same number would be represented as 111.111.222,00, reversing the positions ...

convert HTML string into a React component using a customized parser

I received an HTML string from the server that looks like this: <h1>Title</h1>\n<img class="cover" src="someimg.jpg">\n<p>Introduction</p> My goal is to modify the HTML by replacing the <img class="cover" src="s ...

Is there a way to send a preexisting JSON object to an OPTION in jQuery or JavaScript?

What is the best way to pass a preexisting JSON as a data value in an HTML option tag? I am aware that I can manually pass individual variables like this: <option data-value='{"name":"rajiv","age":"40"}'>a</option> However, if I ha ...

Is it possible for the *ngIf directive to stop unauthorized users from accessing my admin page through their browsers?

When the *ngIf directive is set to false, a certain element or component will not be included in the DOM. For example, let's say there is a component that displays admin tools and should only be accessible to authorized users (administrators). Will se ...

Utilizing *ngIf for Showing Elements Once Data is Completely Loaded

While working on my Angular 2 app, I encountered an issue with the pagination UI loading before the data arrives. This causes a visual glitch where the pagination components initially appear at the top of the page and then shift to the bottom once the data ...

Error: The context does not have a definition for React

import './App.css'; import ComponentC from './components/ComponentC'; export const UserContext = React.createContext() function App() { return ( <div className="App"> <UserContext.Provider value={& ...

Embed a partial view within a Jquery modal dialogue box featuring two distinct models

I am working on a room-booking project. In my View, I have a model of rooms that displays the room ID and its characteristics using a foreach loop: @model IEnumerable<Room> <div class="roomConteiner"> @foreach (Room room in Model) ...

Exploring the focus() method of refs in Vue 3

I'm struggling to comprehend why my straightforward test case keeps failing. As I delve into the world of testing in Vue, I've created a simple test where the element.focus() is triggered onMount(() => /* see implementation ...

Using the ESNEXT, Gutenberg provides a way to incorporate repeater blocks that

If you're like me, trying to create your own custom Gutenberg repeater block with a text and link input field can be quite challenging. I've spent hours looking at ES5 examples like this and this, but still feel stuck. I'm reaching out for ...

Transform ajax functionality into jquery

I need help converting an AJAX function to a jQuery function, but I'm not sure how to do it. function convertToJquery() { // Create our XMLHttpRequest object var hr = new XMLHttpRequest(); // Set up variables needed to send to PHP file var ur ...

Sending data to another page in React Native can be achieved by passing the values as parameters

I am currently working on passing values from one page to another using navigation. I have attempted the following code: this.props.navigation.navigate('welcome', {JSON_ListView_Clicked_Item:this.state.email,})) in the parent class where I am s ...

Performing an asynchronous POST request in JavaScript

Hey there, I successfully managed to implement a post request using ajax for my submit functionality. However, I am now looking to make this asynchronous to account for any delays in processing by my php file. Unfortunately, I am struggling to figure out h ...