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

Transform the object into JSON while excluding specific (private) attributes

I recently started using dean edwards base.js for organizing my program into objects. I must say, base.js is truly amazing! But now I have a question that doesn't require prior knowledge of base.js to answer. Within one of my objects, I have a proper ...

Create a graph that can retrieve and showcase information stored in a Rails database

Is there a way to incorporate a graph into a Ruby on Rails application that can access and show data from a database file (.rb)? If so, what would be the most optimal approach for achieving this? ...

Analyzing registration details stored in an array against user login credentials

With two buttons available - one for sign up and the other for log in, my goal is to gather input form values from the sign-up section into an array. Following this, I aim to compare the user input from the sign-up with that of the log-in, informing the us ...

Explore the contents stored within the slots of S4 objects

Currently, I am working with a package that provides me with an S4 object containing multiple slots. Typically, these objects are easily accessed using s4obj@portfolio. However, my challenge lies in trying to extract a vector from this slot. The specific ...

How can I implement Javascript for tracking webshop activity and affiliate links across multiple websites?

I operate a small front end for a webshop where I receive 5% of the sale amount for every customer who makes a purchase after being referred from my website. However, I am struggling to track these customers and need help in setting up a system to monitor ...

Loading a specific number of rows in Datatables upon page loading: How to do it?

Recently, I came across a code snippet that uses AJAX to retrieve data from a specific URL and then displays the information in a table. However, I have a requirement to only load and display the first 10 rows of data during the initial page load process. ...

Passing Props in Material-UI v5xx with ReactJS: A Beginner's Guide

Struggling with the fact that useStyle() isn't functioning properly in my material-UI v5xx version, I found myself at a loss on how to pass props in this updated edition. In Material-UI v4, it was as simple as: const Navbar = () => { const [open ...

Text that changes within a set-sized box

I'm working with a fixed-size div that contains dynamically generated text. Is there an easy method using DOJO or plain Javascript to truncate the text before the end of the div and add "..."? How can I accomplish this regardless of the font size bein ...

Hydration has finished, but there are some discrepancies - Utilizing Ascii art within a vue component

I encountered an issue with displaying ascii art in the {{ name }} section of my component. While developing, a Vue warning popped up: Hydration text content mismatch in <pre> Followed by an error message: Hydration completed but contains mismatch ...

Trigger the scrolling of one div when another div is scrolled

Link to Jsfiddle I'm attempting to activate my current scroll while I am outside that scroll, specifically in #DivDet Here is the code snippet of what I have tried so far: $("div#DivDet").scroll(function () { // Still trying to figure out what ...

What is the process for setting up a banner on one page that will automatically be reflected on all other pages?

Is there a way to have a banner in a div and display it on the home page so that it automatically appears on all other pages without needing to place the code on each page individually? Any assistance would be greatly appreciated :) ...

PHP is not receiving AJAX POST requests through the $_POST method

I am currently working on a Firefox OS app and I am facing the challenge of using the OpenBadges API instead of PHP, which would have simplified the process. The issue I am encountering revolves around my data not being received by my PHP script after sen ...

Missing Cookie in request using NodeJS and NextJS

Struggling with integrating cookies in a fullstack app I'm developing using Node for backend and NextJS for frontend on separate servers. The challenge lies in getting the browser to attach the cookie received in the response header from the node serv ...

Utilizing regular expressions in Javascript to retrieve multiple instances

This paragraph contains a specific string txt = "Local residents o1__have called g__in o22__with reports..."; that requires extracting numbers between each occurrence of o and __ If we use the following regex: txt.match(/o([0-9]+)__/g); We will obtain ...

Reversing the order of input-group-addon and input in bootstrap on mobile devices

I attempted to adjust the layout of a bootstrap input-group-addon on mobile devices by using two input elements and manipulating their display and visibility properties. From a design standpoint, I achieved the desired result as the input is now positione ...

Android code to mimic GPS functionality

I need some assistance with coding for my project that merges Android with a web application. Specifically, I want to send GPS coordinates from the Android phone to the web application in order to display the location. I am not well-versed in Android cod ...

Using socket.io and express for real-time communication with WebSockets

I'm currently working on implementing socket.io with express and I utilized the express generator. However, I am facing an issue where I cannot see any logs in the console. Prior to writing this, I followed the highly upvoted solution provided by G ...

Decompose JSON String array into separate strings and integers

Using PHP to retrieve data from a MySql DB, the information is returned in JSON format as shown below: 06-15 15:20:17.400: E/JSON(9865): {"tag":"get_game_state","success":1,"error":0,"GameState":{"monster":"Troll","qty":"1","exp":"0"}} The JSON data is t ...

Incorporating an external script within a Next.js application

I've been having trouble incorporating an external JavaScript source into my Next.js application and I keep encountering the following error: Failed to execute 'write' on 'Document': It isn't possible to write into a documen ...

Enhance Your jQuery Skills: Dynamically Apply Classes Based on URL Like a Pro!

Here is an example of HTML code for a progress meter: <div class="col-md-3" style="margin-left: -20px;"> <div class="progress-pos active" id="progess-1"> <div class="progress-pos-inner"> Login </div> </di ...