Display the entire pathway of objects in the array

Hello everyone

I am facing a challenge with an array of objects. I need to display the path of each node value and ultimately print the key and value for a specific node by name.

Presenting the following array of objects in JSON format:

[{
    "Name": "2007",
    "Elements": [{
            "Name": "country1",
            "Elements": [{
                "House": "house1",
                "water": 1.8
            }],
            "Data": {}
        },
        {
            "Name": "country2",
            "Elements": [{
                "Name": "city2",
                "Elements": [{
                    "Name": "neighbourhood2",
                    "Elements": [{
                        "House": "house2",
                        "water": 2.8
                    }]
                }],
                "Data": {}

            }],
            "Data": {}
        },
        {
            "Name": "country3",
            "Elements": [{
                "House": "house2",
                "uni bill": 3.8
            }],
            "Data": {}
        }
    ],
    "Data": {}
}]

The desired output should resemble this:

2007 > country1 > house > water: 1.8
2007 > city2 > neighbourhood2 > house2 > electricity: 2.8
2007 > country3 > house > uni bill: 3.8

++++++++++++++ updated +++++++++++++++

function objectToPaths(data) {
    var validId = /^[a-z_$][a-z0-9_$]*$/i;
    var result = [];
   doIt(data, "");
    return result;

    function doIt(data, s) {
      if (data && typeof data === "object") {
       if (Array.isArray(data)) {
          for (var i = 0; i < data.length; i++) {
            doIt(data[i], s + "");
          }
        } else {
          for (var p in data) {
            if (validId.test(p)) {

              doIt(data[p], s + " > " + data[p]);
             } else {
              doIt(data[p], s + "");
           }
          }
        }
      } else {
        result.push(s);
      }
   }
 }

This is my attempt at rewriting a found function, but I'm not getting the expected outcome.

+++++++++++++++++++++++ end of update +++++++++++++++++++++++

Your assistance would be greatly appreciated.

Many thanks in advance

Answer №1

To achieve your goal, you need to implement a Depth First Traversal function that recursively prints properties:

function display(arr, path) {                              // display function takes an array and an accumulated path from which it will start displaying
  arr.forEach(function(obj) {                            // iterate through each object obj in the array
    if(obj.Elements) {                                   // check if the object obj has sub elements
      display(obj.Elements, path + " > " + obj.Name);      // call display on those elements, providing the absolute path to this object
    } else {                                             // if it is a leaf node
      const details = Object.keys(obj)
        .filter(key => key !== "House")
        .map(key => `${key}: ${obj[key]}`)
        .join(', ')
      console.log(path.slice(3) + " > " + obj.House + " > " + details);    // print the accumulated path along with the House property of this object (removing the first 3 characters from path)
    }
  });
};

var data = [{"Name":"2007","Elements":[{"Name":"country1","Elements":[{"House":"house1","water":1.8}],"Data":{}},{"Name":"country2","Elements":[{"Name":"city2","Elements":[{"Name":"neighbourhood2","Elements":[{"House":"house2","water":2.8}]}],"Data":{}}],"Data":{}},{"Name":"country3","Elements":[{"House":"house2","uni bill":3.8}],"Data":{}}],"Data":{}}];

display(data, "");

Answer №2

If you utilize a function to iterate through and gather the path to the final object, you can easily navigate through nested data structures.

function iteration(array, path) {
    path = path || [];
    array.forEach(function (o) {
        if (o.Elements) {
            return iteration(o.Elements, path.concat(o.Name));
        }
        Object.keys(o).forEach(function (k) {
            if (k !== 'House') {
                console.log(path.concat(o.House, k).join(' > ') + ': ' + o[k]);
            }
        });            
    });
}

var data = [{ Name: "2007", Elements: [{ Name: "country1", Elements: [{ House: "house1", water: 1.8 }], Data: {} }, { Name: "country2", Elements: [{ Name: "city2", Elements: [{ Name: "neighbourhood2", Elements: [{ House: "house2", water: 2.8 }] }], Data: {} }], Data: {} }, { Name: "country3", Elements: [{ House: "house2", "uni bill": 3.8 }], Data: {} }], Data: {} }];

iteration(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

ReactJS Components failing to load on initial site visit, only appearing after refreshing for the second time

var img; var dateFormat = require('dateformat'); var count; let arrayIMG = [] var storage = firebase.storage(); var storeRef = storage.ref('images/') const config = { ... }; if (!firebase.apps. ...

The dropdown feature stores and displays only the initial value

After resolving my previous question (link), I am now facing a new issue where the value of the name field is only reflecting the first item in the dropdown list. Let me explain further. I have two dropdown menus, where selecting an option in one (A) dyna ...

What is the best way to pass or declare elements of an array in C language?

After creating a program designed to process specific elements from an array of double purchase within a function, I encountered an issue when trying to call the function in my main code: float beverages () { char response; double purc ...

What is the best way to display a JSON array in Angular 4?

Check out this JSON structure: -------------------------------------------------- "id": 2, "user": { "id": 1, "name": "User", "surname": "User", "email": "<a href="/cdn-cgi/l/email-protection" ...

Implementing JSON response in email functionality using Ajax and PHP

I've encountered a problem with my contact form. I'm receiving error messages for invalid email and incomplete fields, but I'm not getting a success message. As a result, the email is being sent twice without any confirmation message (I&apos ...

Can we enhance this JavaScript setup while still embracing the KISS principle (Keep it simple, Stupid)?

I have completed the following tasks: Ensured all event handlers are placed inside jQuery DOM ready to ensure that all events will only run Defined a var selector at the top of events for caching purposes Please refer to the comments below for what I be ...

How to attach additional attributes to a Rails model without persisting them in the database in Rails

When rendering a view based on a JSON object representing a Rails model, I encountered issues with including fields not part of the model. To resolve this, I added the extra fields in the controller as shown in Example 1: #Controller events = Event.where( ...

Arranging routes in node.js like a pro

const express = require('express'); const router = express.Router(); router.use(function(req, res, next){ console.log(req.user) if(!req.user){ res.redirect('/login'); }else{ res.locals.username = req.user.us ...

Navigating a multi-layered associative array

I have an array that I want to iterate through (This is the output of print_r): Array ( [GetRecentCasesResult] => Array ( [CaseHistory] => Array ( [0] => Array ( [caseNumber] => CAS-00305-Q0S7Y5 ...

Catch the return of the transition event

My website is built on asp net core, with all pages displayed as partialviews to create a spa model without relying on angular or other frameworks. By switching partialviews, I can easily modify the page's url using window.history.pushState ("objec ...

Is there a way to send a variable to the alert function using $.ajax()?

I need assistance with confirming the deletion of a record. When the user clicks on the button, it should send the value 'Yes' to a $_POST request in PHP for deleting the record. However, instead of working as expected, it is showing me the JavaS ...

What is the mechanism Angular utilizes to determine the exact location of directives within a webpage?

Can you explain how Angular is able to locate the directives on a webpage and establish connections with or observe those elements? I've searched through the DOM reference, but it seems like methods like getElementbySomething and querySelectorAll may ...

Having trouble with Bootstrap 4 dropdowns: Uncaught TypeError issue?

I am having trouble getting my Bootstrap 4 dropdown menu to function correctly. Despite trying various solutions from other threads, I continue to encounter an 'uncaught TypeError: cannot read property 'fn' of undefined' error in bootst ...

Guide to updating state within a nested object

Is there a way to update nested object states in React using the useState() hook? import React, {useState} from 'react' const MyComp = () => { const [colors, setColors] = useState({colorA: 'RED', colorB: 'PURPLE'}); ...

Determining browser compatibility with TokBox - a guide

Can Tokbox detect browsers and display a "not supported" page? I noticed in Tokbox's demo video page that they are able to do this, but I searched their documentation and couldn't find instructions on how to achieve it. Can anyone provide assist ...

Transforming Json data into an Object using Angular 6

https://i.stack.imgur.com/JKUpL.png This is the current format of data I am receiving from the server, but I would like it to be in the form of an Object. public getOrder(): Observable < ORDERS > { return this._http.get < ORDERS > (`${thi ...

Discovering the wonders of Angular's Heroes Tour: What's the magic behind adding the ID in the addHero function

During Angular's official tour of heroes tutorial (https://angular.io/tutorial/toh-pt6), an interesting observation was made. When the addHero method is called, only the hero's name property is passed as an argument. However, it seems that a new ...

Updating a particular value within a JSON file

I'm searching for a method to locate a specific json value by its name and set it to null. The json file's structure can vary, it is not always consistent. Let's assume the json appears like this: [ { "id": "1111", ...

Having trouble retrieving the `Content-Disposition` information from the backend response

I've been attempting to retrieve the value of Content-Disposition from the backend response, but unfortunately, I have not been successful. Here is the code I have been working with: public getQuoteImage(sharedQuote):Observable<any> { retu ...

What is the best way to send unprocessed JSON strings to the DeployR WebAPI?

Scenario: Currently, I am dealing with a situation where I have a series of inputs that need to be sent to the deployr server. Among these inputs, some are simple strings while others are JSON strings that are processed by the R script using fromJSON func ...