What is the best method for looping through a JavaScript object in cases where the value itself is an object?

Updated query. Thanks to @WiktorZychla for sparking my Monday morning thoughts on recursion. The revised code is functioning correctly now.

Assuming I have a dummy object structured like this:

const dummy = {
    a: 1,
    b: 2,
    c: {
        d: 3,
        e: {
            f: 4
        }
    },
    g: 5
};

I can traverse through it using the following function:

const xavier = (value, s) => {
  for (const key in value) {
    if (value.hasOwnProperty(key)) {
      if (typeof value[key] === 'object' && value[key] !== null) {
        xavier(value[key], s + '.' + key);
      } else {
        console.log(s + '.' + key + ' ' + value[key]);
      }
    }
  }
};

The output of this function is as follows:

.a 1
.b 2
.c.d 3
.c.e.f 4
.g 5

Answer №1

After putting in the hard work, I successfully created a function that can loop through any object. This function allows you to specify how many levels of iteration you want to occur. Take a moment to review it below:

arr = [];
obj = {
  a: 1,
  b: 2,
  c: {
    d: 3,
    e: {
      f: 4
    }
  }
}
function iter(x){
for(i in x){
if(typeof(x[i])=="object"){
iter(x[i]);
}else{
arr.push(x[i]);
}}}
iter(obj);
document.write(arr.join(','));
<!DOCTYPE html>
<html>
<body></body>
</html>

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

What could be causing issues with my jQuery POST call?

I am attempting to establish authentication with a remote service using jQuery. Initially, I confirmed that I can accomplish this outside of the browser: curl -X POST -H "Content-Type: application/json" -H "Accept: appliction/json" -d '{"username":" ...

Struggling to dynamically update array values by comparing two arrays

I am faced with a scenario where I have two arrays within an Angular framework. One of the arrays is a regular array named A, containing values such as ['Stock_Number', 'Model', 'Type', 'Bill_Number'] The other arr ...

Pattern matching using regex can also be used to restrict the number of characters allowed

Having some trouble with regex to match a specific pattern and also limit the number of characters: Let's say I have allowed number prefixes: 2, 31, 32, 35, 37, 38, 39, 41, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 I only want numb ...

AngularJS - Always keep an eye on a group of items

Looking to create a custom watcher for a collection within my application, I initially believed that Angular would have all the necessary tools at my disposal. I had access to $watch, both shallow and deep, as well as $watchCollection. A $digest cycle was ...

Issue with VueJS where changes made to properties in the mounted hook do not properly trigger the

I'm working on a VueJS component that features a button with computed properties for its class and text. These properties change every time the button is clicked, updating smoothly with each interaction. However, I've encountered an issue when at ...

What is the process to activate strict mode for my entire package without applying it to dependencies?

Previously, I would always start my JavaScript files with "use strict"; to enable the strict mode. However, I am now faced with the task of applying this change to over 200 files in my NodeJS package, which seems like a daunting process. Is there a way to ...

Is there a way to simultaneously modify several data variables within a Chart.js label?

I'm currently working on dynamically updating a line chart with two data entry points using the variable name "data." Take a look at the code snippet below: var lion = new Chart(ctx2, { type: "line", data: { labels: ["Apr", "May", ...

choosing a specific element with jQuery to be used for future purposes

I'm having some trouble with the following code snippet: var star = $("._container > favorite"); var symbol = $(star.parentNode.parentNode).attr("symbol"); var exchange = $(star.parentNode.parentNode).attr("exchange"); After running ...

When working with jQuery, I encountered the error message "is not a function" because I mistakenly tried to use a function more than

While working on a pager, I encountered an issue with a function that is initially invoked when the document loads. However, when attempting to use it a second time, an error "is not a function" occurs. I am curious about the reason behind this phenomenon. ...

What is the method for displaying an array separately for each item in JSON using JavaScript?

The issue arises when using for (let pet of person.pets) loop. In my JSON data, the "pets" field is an array but instead of getting a single array for each object, I am getting all pet arrays for every object in the JSON file. The desired outcome is to h ...

How can images from a dynamic table be converted to base64 format in Vue.js and then sent in a JSON file?

Hello everyone, I'm facing an issue with a dynamic table where I need to add multiple rows, each containing a different image. I attempted to convert these images to base64 format and save them in a JSON file along with the table data. However, the pr ...

What are the steps to determine if a radio has been examined through programming?

In my form page, users can input an ID to fetch profile data from a MySQL database using AJAX. The retrieved data is then displayed in the form for editing. One part of the form consists of radio buttons to select a year level (e.g., "1", "2", "3", etc). ...

Arrange and display similar objects together

I have a list of items in a listView that need to be visually grouped based on their class, displayed within boxes. For example, I have 5 items with the following classes: <div class="1"></div> <div class="1"></div> <div class= ...

Cut off all information beyond null characters (0x00) in Internet Explorer AJAX responses

When using Internet Explorer (IE6, IE7, and IE8), null characters ("0x00") and any subsequent characters get removed from ajax responses. Here's the code snippet that showcases a loop of AJAX requests: var pages = 10; var nextnoteid = 0; for (isub ...

Looking for a solution to eliminate Parsing Error: Unexpected Token when developing with React? I've already implemented ESLint and Prettier

Currently, I am working on building a form in React with MUI. Below is the code snippet that I have been working with: const textFields = [ { label: 'Name', placeholder: 'Enter a company name', }, { label: 'Addres ...

Javascript Error: Page reload interrupted by Broken Pipe IOError [Errno 32]

I am facing an issue with my javascript function that sends a signal to my flask app for recalculating figures using ajax. Upon successful figure production, I want to reload the page with updated figures by adding a version number to the filename (using & ...

Display modal within a React list

I need to display a list of items with an edit button for each item, which should trigger a modal showing the details of that specific item. Initially, I had a single modal component in the parent element and passing the visible values to the parent state ...

Tips for showcasing the chosen option from an autocomplete input field in a React application

Currently learning React and working on a search feature for a multi-form application. The goal is to allow users to search for a student by first name, last name, or student ID using an autocomplete text field. The options for the autocomplete text field ...

What are the different applications of npm packages?

Is it possible to use npm packages in any Javascript runtime environment? I have experience using them in Angular and Node, but are they universally compatible across all environments? Edit: To those who downvoted this post, as a newcomer seeking assistan ...

React - Error occurred when parsing module: Unexpected Token. It is recommended to use a suitable loader to manage this file format

As a beginner in using React, I might be making obvious mistakes and I apologize for that. After researching similar bugs on various platforms like StackOverflow and GitHub, I couldn't find a solution that works for my specific issue. Here is the erro ...