What is the easiest method to iterate through nested objects within an object?

Hey there! I'm working on implementing a "your cart" feature for an ecommerce website in my project, and I could use some assistance with coding to loop through an object within an object. Below is the code snippet I've been working on:

var products = {
  product1: {
    name: "Balenciaga Black Shoes",
    quantity: 2,
    price: 50,
    size: "L",
    shipping: 20
  },
  product2: {
    name: "Gucci Pink Bag",
    quantity: 1,
    price: 70,
    size: "Big",
    shipping: 20
  }
};

function myFunc() {

  for (const key in products) {
    for (const key2 in key) {

      console.log(`${key2}: ${key[key2]}`);
    }
  }
}

myFunc()

Answer ā„–1

You are currently iterating over the key name directly, which is just a string:

for (const key2 in key) {

Instead, iterate over the property indicated by that key:

for (const key2 in products[key]) {

Similarly, make sure to reference that property when displaying output:

console.log(`${key2}: ${products[key][key2]}`);

To provide a clearer understanding of the property hierarchy and values:

console.log(`${key}:${key2}: ${products[key][key2]}`);

For instance:

var products = 
{
    product1: {
        name: "Balenciaga Black Shoes",
        quantity: 2,
        price: 50,
        size: "L",
        shipping: 20
    },
    product2: {
        name: "Gucci Pink Bag",
        quantity: 1,
        price: 70,
        size: "Big",
        shipping: 20
    }
};

function myFunc() {

    for (const key in products) {
        for (const key2 in products[key]) {

            console.log(`${key}:${key2}: ${products[key][key2]}`);
        }
    }
}

myFunc();

Answer ā„–2

Have you considered storing your products in an array instead of an object? In any case, the approach here is to iterate through all the values of your products object and then iterate through all the keys of each product:

let products = [
  {
    name: 'Balenciaga Black Shoes',
    quantity: 2,
    price: 50,
    size: 'L',
    shipping: 20,
  },
  {
    name: 'Gucci Pink Bag',
    quantity: 1,
    price: 70,
    size: 'Big',
    shipping: 20,
  },
];

for (const product of products) {
  for (const key in product) {
    console.log(`${key}: ${product[key]}`);
  }
}

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

Innovative react route

Currently, I am in the process of learning about dynamic react routes. In the code example I am working on, there are different buttons for each task. The goal is to render the WorkDetails component when a button is clicked. However, it seems to not be fun ...

Unable to modify the name of an element's class due to restrictions in JavaScript

I am trying to switch the class of an element from score -box1 to score -box1.-active. I defined a constant $target in order to access the class score -box1, however it is not functioning as expected. const $target = document.getElementByClassname('sc ...

Using VueJS to iterate through an array while applying a condition to filter out certain elements (combining v-for with v-if)

I'm currently working on a v-for loop to display two columns of card elements. The idea is to print the current element and the next one in a row if the index is even, skipping the elements with odd indexes. This is what my code looks like: <temp ...

Methods for organizing an array of objects by a specific key in JavaScript, but in the case of duplicate values, the objects can be sorted by a different

I'm struggling to sort an array of objects by two different keys. I need to first sort the array by price, and if there are multiple items with the same price, they should then be sorted by time. Here's what my array looks like: var myArr = [ {&q ...

Check for mobile browser without having to refresh the page

Currently, I am facing an issue with closing the sidebar when the user clicks on Click Me button in mobile view using flexbox layout. The problem arises because the page needs to be refreshed for it to recognize if it's in mobile mode or not by utiliz ...

Is there a convenient HTML parser that is compatible with Nativescript?

I have tested various libraries like Jquery, Parse5, and JsDom, but unfortunately they are not compatible with nativescript. Jquery relies on the DOM, while Parse5 and JsDom require Node.js which is currently not supported by nativescript. I am in need of ...

The persistent issue persists with the Sails.js Node server where the req.session remains devoid of any data, despite utilizing

Currently, I have an Ember app running on http://localhost:4200 and a Sails app running on http://localhost:1337. In order to set up a pre-signup survey policy in my Sails application, I have the following code in /api/controllers/ProcessSurveyController. ...

"Learn how to clear an input field using jQuery with this simple guide

I've gone through a few discussions, such as this one and that one, but I'm still struggling to clear the input field after submission. What is the simplest way to achieve this? This is my current approach: $(document).ready(function(){ $(& ...

Implementing a callback function following the completion of file reading in Phonegap

I have been facing this issue for quite some time now and I need assistance in finding a solution: When it comes to developing an android app, I rely on the phonegap framework. There is an async function called readFromFile() that reads a json file store ...

Tips for receiving user input with custom values and assigning them to variables through multiple selection criteria using Jquery

I am encountering an issue with a form that contains multiple selection blocks. I am attempting to extract the values of each block criteria on click in order to send it to a database. However, every time I click on a block, my script retrieves all the val ...

Live calculation feature for dropdown menus

I have a form where I need to calculate the total result after submission. The package and event ID should be added together, and the guest field should always be calculated (guest value * 5). The final result should be displayed in <div id="result"> ...

Form an object using elements of a string array

Trying to convert a string array into an object. The string array is as follows : let BaseArray = ['origin/develop', 'origin/master', 'toto/branch', 'tata/hello', 'tata/world']; I want the resulting obje ...

What is causing express.js not to authenticate properly?

I'm currently in the process of developing a server application using node.js, which is up and running on localhost:8080. As I attempt to make a login request, I've encountered an issue where one method works while the other fails. My suspicion i ...

Transferring extra data from jQuery autocomplete to a PHP script

Hey there! I'm wondering if it's possible to pass extra parameters from jQuery autocomplete to a PHP page, which would then use them to query a database and return the results. While I know how to send the typed term from the input box, I'd ...

Weird State / Unusual Effectiveness with NextJS Links

I'm encountering some unusual behavior in a personal project I'm working on. The project is a recipe website with buttons at the top that lead to different pages querying Firebase for recipe data. In the Index.js file, Firestore queries pass pro ...

What is the best way to handle .jsx files in my library bundling process with Rollup?

Currently, I am in the process of developing a component library using storybook and rollup. Here is the configuration file rollup.config.mjs /* eslint-disable import/no-extraneous-dependencies */ import peerDepsExternal from 'rollup-plugin-peer-deps- ...

Communicate with Internet Explorer's JavaScript console using VBA within Excel

I'm encountering an issue when trying to send a basic http post request. While it functions perfectly when sent via ajax in the Internet Explorer console, I'm running into difficulties when attempting to do so in VBA. After some investigation, I& ...

JavaScript array contains duplicate values

I have developed a custom Asp.Net user control. To keep things simple, I have omitted some of the HTML code. <asp:Panel ID="PanelInputControl" runat="server" CssClass="input-control input-period"> <div ID="InputWrapperMonth" runat="server" c ...

The state value is not preserved after redirecting to another page

For the past couple of days, I've been struggling with an issue and I can't seem to figure out what I'm doing wrong. My goal is to create a login page that redirects users to the dashboard after they log in. To maintain consistency acros ...

Implement Javascript Event Listener

I'm a newcomer to the world of javascript and Iā€™m struggling to understand why the code below isn't functioning correctly: var displayMessage = document.getElementById("notification"); displayMessage.addEventListener("click", function() { ...