Traveling within a layered object

Currently, I'm working with an object and iterating through it to retrieve outputs as shown below:

var obj = {
  "first": {
    "Bob": {
      "1": "foo",
      "2": "bar"
    },
    "Jim": {
      "1": "baz"
    }
  },
  "second": {
    "Bob": {
      "1": "qux"
    },
    "Jim": {
      "1": "quux"
    },
  },
}

for (let position in obj) {
  console.log(`In ${position} position`);
  let pos = obj[position];
  for (let name in pos) {
    person = pos[name];
    for (let item in person) {
      let thing = person[item];
      console.log(`${position} ${name} ${item} ${thing}`)
    }
  }
}

While this method works, it seems a bit convoluted due to the nested for loops. Is there a more elegant solution using ES6/ES7+ features?

Answer №1

To efficiently handle nested objects, one can implement a combination of iterative and recursive methods. By examining each item in the object and checking if it is an object itself, you can continue iterating through the nested structure while keeping track of the path to each object.

Subsequently, this path information can be utilized alongside the corresponding value.

function iterateObject(object, path = []) {
    Object.keys(object).forEach(key => {
        var temp = path.concat(key);
        if (object[key] && typeof object[key] === 'object') {
            iterateObject(object[key], temp);
            return;
        }
        console.log(path.join(' > '), object[key]);
    });
}


var data = { first: { Bob: { "1": "foo", "2": "bar" }, Jim: { "1": "baz" } }, second: { Bob: { "1": "qux" }, Jim: { "1": "quux" } } };

iterateObject(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Having difficulty duplicating a button with a click event using jQuery

I have implemented a button that reveals a phone number when clicked using the code below: var shortNumber = $("#phone_ch").text().substring(0, $("#phone_ch").text().length - 12); var onClickInfo = "_gaq.push(['_trackEvent', 'EVENT-CATEGOR ...

Invoke a codebehind function using jQuery

I am encountering an issue while trying to complete a simple task. I am attempting to pass values to a code behind method, perform some calculations, and then return the result. Initially, I started with a test method but have not been successful in making ...

Where did my HTML5 Canvas Text disappear to?

I am encountering a common issue with my code and could use some guidance. Despite numerous attempts, I can't seem to figure out why it isn't functioning properly. To better illustrate the problem, here is a link to the troublesome code snippet o ...

I would like to exclude the item within my ng-repeat loop using ng-if

I'm attempting to utilize ng-if within ng-repeat in order to create Accordions. Depending on the condition value, I want certain items to be skipped in the ng-repeat. For example, if item.condition is true, then only display the accordion. The code b ...

Retrieve the JavaScript object that was initialized within a function

As I venture into the world of working with javascript objects and php objects, I've encountered an issue. While everything seems to be functioning correctly so far, I'm having trouble accessing the javascript object created in the ajax success r ...

Creating a stunning 2D image from a 3D scene through the power of raytracing with webgl and three.js

My goal is to project a 3D scene onto a 2D plane using ray tracing. Although my ultimate aim is volume rendering, I am currently struggling with the basics. I have set up a three.js scene with the viewing plane attached to the camera in front of it. The S ...

Disabling the camera feed in a React application

Attempting to turn off the webcam using javaScript in React has been a bit challenging. Whenever I shift to a new component or when a component is destroyed, my react component immediately moves to the next page, but the webcam light remains on in the new ...

What are the best ways to customize exported and slotted components in Svelte?

Is there a similarity between Svelte slots and vanilla-js/dom functionality (I'm having trouble with it). In html/js, I can achieve the following: <style> body {color: red;} /* style exposed part from outside */ my-element::par ...

Is this the proper formatting for JavaScript code?

Having trouble changing the CSS of elements that match b-video > p with an embed element using JQuery. Here's my code: $('div.b-video > p').has('embed').attr('style','display:block;'); Can anyone help me ...

Creating a dynamic 3D pie chart with Highcharts and JSON data

I am attempting to create a 3D pie chart using HighChart with JSON data. Despite enabling the 3D option, it only displays in 2D. Here is an example of the 3D pie chart I am trying to achieve: Could someone please help me identify what might be missing in ...

What is the best way to transfer variables between PHP and an external JavaScript file?

I need to transfer 2 variables (which store data for a chart) to an external JS file that contains the chart settings. In my PHP code, I have: <script type='text/javascript'> var final_values = '$final_values'; var final_names = ...

I'm having trouble getting the JADE tag to render in Express script. Can anyone help me

I am trying to include client-side script in my JADE template and so far I have: extends layout script. function collect_data() { var transitions = {}; $( ":checkbox:checked" ).each(function (index, element) { //// some code ...

Guide to utilizing various functions, with equations, within a specific scope in angularJS

myApp.controller('incomeController', ['$scope', function($scope) { $scope.pay = 0; $scope.hours = 0; $scope.tax=0.19297; $scope.total = function() { return $scope.pay * $scope.hours;} $scope.taxTotal ...

Implementing batch processing and scheduling API requests in node.js using async functions

I am currently working on analyzing a social network graph, specifically focusing on creating a "six degrees of separation" tree based on adjacency lists obtained from an API. The challenge lies in the fact that there is a large number of individuals in t ...

Using jQuery, identify when any of the elements within every function are missing

In my JavaScript file, I have the following code snippet: var aryYears= []; $(".year").each(function(){ aryYears.push($(this).val()); }) This allows me to pass an array of years as a parameter in the saveChanges function. I want to make ...

In Firefox, long strings are automatically truncated, while in Google Chrome they display perfectly without any truncation

Here is a block of code where I am using a web service to retrieve a JSON string. It is encapsulated in an XML tag, which I then read and parse with jQuery's parser jQuery.parseJSON(xml.getElementsByTagName("string")[0].firstChild.nodeValue); $.ajax ...

Calls to the function are piling up

There is a bootstrap modal that displays a confirmation message. If the 'accept' button is clicked, a function is called with an id. If the 'cancel' or 'close' button is clicked, the modal closes. The problem arises when the m ...

Employing the Confirm() function within the onbeforeunload() event

Is there a way to prompt the user with a confirmation box before exiting a page using JavaScript? If the user clicks "OK", a function should be executed before leaving the page, and if they click "Cancel", the page should remain open. window.onbeforeunloa ...

PostgreSQL dynamic query with Node.js

I am currently developing a note-taking app using REACT. My focus is on tracking only the changes made by the user to the note, rather than the current state of the note. For properties that have not been altered, I intend to send them as an empty string ...

Issue encountered while attempting to adjust a date (the modification was incorrect)

I am currently working on developing a calendar feature using Angular. Part of this project involves implementing drag and drop functionality to allow users to move appointments from one day to another. However, I have encountered a strange issue. When at ...