javascript: explore the contents of a multi-level object

In my JavaScript code, I am working with an object structured like this:

Cards:Object
     |->Pack:Object
            |->Spades:Array[60]
                     |-> 0: Object
                          |->  Card_img: "www.test1.com"
                               Card_type:"9"
                         1:
                          |-> Card_img:"www.test2.com"
                              Card_type:"8"

I am trying to figure out how to loop through all the key-value properties in Spades {0, 1, etc} and return something like {card_img: www.test1.com, card_img: www.test2.com}

Here is the code snippet I have written:

Object.keys(cards).forEach(function (key) {
  console.log(key); // This gives me 'Card', but how can I drill down further?
});

When I try

Object.keys(cards.Packs).forEach(function (key)
I get Object.keys called on non-object.

Answer №1

While it's not possible to have an object with duplicate keys, you can still store each card in an array.

// example of a cards object
var cards = {
  pack: {
    spades: [
      { card_img: 'blah.png', card_type: '9' },
      { card_img: 'blah.png', card_type: '10' },
    ]
  }
};

// initializing an array for spades
var spades = [];

// iterating through each "pack" property
for (i in cards.pack) {

  // iterating through each card of this suit
  for (j in cards.pack[i]) {
    spades.push(cards.pack[i][j]);
  }
}

// displaying the cards stored in the array
console.log(spades);

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

Executing vitest on compiled javascript files

Currently facing issues running vitest on compiled JavaScript. Numerous errors are appearing, such as: TypeError: Cannot read properties of undefined (reading 'spyOn') TypeError: Cannot read properties of undefined (reading 'mock') and ...

Learn the step-by-step process of utilizing the MySQL parameter array within a MySqlCommand to efficiently execute commands and seamlessly

I currently have a mysqlcommand and mysqlparameter array [] MySqlParameter[] param = new MySqlParameter[]{ // parameters listed here }; I am now attempting to assign the command parameter for this array. How can I achieve this without encounte ...

Utilizing Class Methods within an Object (Node.js)

Seeking to streamline my code and reduce the number of if statements, I've been working on optimizing this code within a Class. if (spot.charAt(1) === "P") this.#getMovesPawn(row, col, validMoves); if (spot.charAt(1) === "N") this.#getMovesKnight(row, ...

Troubleshooting the issue with an undefined factory in angularjs ui-router

I have been following the examples provided on the UI-Router wiki as well as the sample available at this link: https://scotch.io/tutorials/angular-routing-using-ui-router However, I am facing an issue where the resolved factory is appearing undefined when ...

Managing multiple changes in input values within an object

Looking to update multiple input field values using the handleChange() method with a starter object that includes its own properties. The goal is to assign input field values to corresponding properties within the starter object. However, the current imple ...

Using a TCP server to transfer and store files with node.js

I am managing multiple devices that are continuously sending messages to a TCP Server built in node. The primary purpose of this TCP server is to route certain messages to redis for further processing by another application. I have created a basic server ...

Just released a new npm package called vue-izitheme. It's fully functional from the command line, but for some reason it's not showing up in search results. Any suggestions on how to fix

I released my project, vue-izitheme, two days ago but I can't seem to find it when searching. It is functioning correctly from the command line and has already been downloaded 44 times. Do you have any thoughts on what could be causing this issue? ...

Disabling the scrollTop() effect following a click event with onClick()

Utilizing the scrollTop() event to toggle the visibility of a div at a specific position and also using the onClick() event to permanently hide the div. While the events are functioning properly, an issue arises when scrolling the page causing the div to r ...

Tips for troubleshooting the error "Cannot locate module mp3 file or its associated type declarations"

https://i.sstatic.net/q4x3m.png Seeking guidance on resolving the issue with finding module './audio/audio1.mp3' or its type declarations. I have already attempted using require('./audio/audio1.mp3'), but continue to encounter an error ...

Deactivate CS:GO Dedicated Server using Node.js child_process

I've been attempting to manage multiple Counter Strike: Global Offensive dedicated servers programmatically. The process is running smoothly, however, I am facing a challenge in shutting it down completely. Upon starting the server, two processes are ...

Using Vue to create a single submit() method that works with multiple forms

Having multiple forms with the same logic for validation and submission, I want to streamline my code by creating a single method to handle form actions. Currently, there is redundancy in my code as each .vue file contains the same onSubmit() method. Here ...

Vue.js: Dynamically display buttons in the navigation bar depending on the user's login status through Vuex Store state

I am currently in the process of creating a navigation bar that displays different buttons based on whether the user is logged in or not. To achieve this, I am utilizing Vuex and localStorage to manage the state. My goal is to develop a dynamic menu using ...

What is the best way to adjust the width of these elements for a perfect fit?

I'm currently working on a website where I have arranged squares in a grid layout. My goal is to make these squares perfect, with equal width and height. The only issue I'm encountering is that they tend to change between fitting two and three sq ...

Comparison: Pros and Cons of Multidimensional Lists versus Flat Lists

When working with very large lists of lists in Python to perform mathematical operations, I noticed a significant lag (~20 seconds). This prompted me to compare multidimensional lists with flat lists. Code from timeit import timeit from sys import getsiz ...

Tips for muting console.log output from a third-party iframe

As I work on developing a web application using NEXT.js, I am encountering an issue with a third party iframe that is generating numerous console logs. I am seeking a way to silence these outputs for the iframe. The code in question simply includes an < ...

Limit the minimum date on iOS using javascript

I am currently enhancing the mobile user experience for a website specifically designed for iOS devices. I have incorporated the following code snippet to allow users to select a date: <input type="date" min="2013-09-01"> However, I discovered that ...

Tips for avoiding line breaks in Zapier workflows while working with JavaScript

Hi there, this is my first time posting on StackOverflow so I appreciate your understanding. Here is the problem I'm facing: I have a Zap that retrieves data from a Google sheet and adds it to a JavaScript array in a document. I utilized Zapier code ...

I'm noticing that the dropdown content for all my buttons is identical. What could be causing this

I have encountered an issue with the two buttons placed inside my header. Whenever I click on either button, the content displayed remains the same. https://i.sstatic.net/fk4V8.png https://i.sstatic.net/TCL7H.png It seems that when I click on one button, ...

"There seems to be an issue with the KeyListener function in

The error I'm encountering is: index.html:12 Uncaught TypeError: Cannot read property 'addEventListener' of null I'm unsure about what went wrong. The intention behind the code was to store the result of the selected radio button into a ...

Choose the Matching Array Element and Retrieve the Desired Fields

Can you provide me with information on how to establish the projection for a matched array of objects from a Mongoose query? For instance, consider a Mongoose model structured as follows: var User = new Schema({ name: String, children: [Child] }); v ...