Gather all possible routes within the JSON structure

I am faced with a JavaScript object that contains various data:

{
    "gender": "man",
    "jobinfo": {
        "type": "teacher"
    },
    "children": [
        {
            "name": "Daniel",
            "age": 12,
            "pets": [
                {
                    "type": "cat", 
                    "name": "Willy",
                    "age": 2
                },
                {
                    "type": "dog", 
                    "name": "Jimmie",
                    "age": 5
                }
            ]
        }
    ]
}

My goal is to list out all the paths (keys and array indices) within the object, including their respective parents (e.g., children should be included along with its contents).

gender
jobinfo,
jobinfo.type,
children,
children.0.name,
children.0.age,
children.0.pets,
children.0.pets.0.type,
children.0.pets.0.name,
children.0.pets.0.age,
children.0.pets.1.type,
children.0.pets.1.name,
children.0.pets.1.age

I attempted to write a code for this purpose but encountered issues:

function getPath(object) {
    for (key in object) {
        if (Array.isArray(object[key]) === true) {
            console.log(key)
            getPath(object[key])
        } else if (typeof object[key] === 'object') {
            console.log(key)
            getPath(object[key])
        } else {
            console.log(key)
        }
    }
}

While this code does display all keys in the JSON object, I am finding it challenging to concatenate the paths, particularly in nested elements.

Answer №1

With this updated version, the code now efficiently handles array keys containing numbers such as 'children.0', providing the desired output:

const data = {"gender":"woman","jobinfo":{"type":"engineer"},"children":[{"name":"Sophia","age":10,"pets":[{"type":"bird","name":"Polly","age":3},{"type":"rabbit","name":"Bunny","age":4}]}]};

function extractPath(obj, path) {
  for (let prop in obj) {
    let currentPath = path ? `${path}.${prop}` : prop;

    if (Array.isArray(obj[prop])) {
      console.log(currentPath);
      extractPath(obj[prop], currentPath);
    } else if (typeof obj[prop] === 'object') {
      if (!Array.isArray(obj)) { // exclude logging array keys like children.0
        console.log(currentPath);
      }
      extractPath(obj[prop], currentPath);
    } else {
      console.log(currentPath);
    }
  }
}

extractPath(data);

Answer №2

This method is successful:

const data = {"gender":"man","jobinfo":{"type":"teacher"},"children":[{"name":"Daniel","age":12,"pets":[{"type":"cat","name":"Willy","age":2},{"type":"dog","name":"Jimmie","age":5}]}]};

const getPath = (currPath, item) => {
  console.log(currPath);
  if (Array.isArray(item)) {
    item.forEach((el, idx) => getPath(`${currPath}.${idx}`, el));
  } else if (typeof item == "object") {
    Object.entries(item).forEach(([key, value]) => {
      getPath(`${currPath}.${key}`, value);
    });
  }
};

Object.entries(data).forEach(([key, value]) => {
  getPath(key, value);
});

Essentially, I iterate through each entry in the initial object by utilizing the key as the path at that particular stage while verifying whether the value is an array or object. The function consistently displays the path (to offer the desired outer layers) and proceeds to recursively process the inner layers, adjusting the path accordingly.

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 is the best way to restart the clock in three.js?

I am looking for a way to reset the clock in my game so that each time I call clock.getElapsedTime(), it provides a fresh time from the moment I reset the clock. This would be particularly useful when restarting a game level or scene for the second time. ...

"The interconnection between NetBeans, jQuery, and AJAX is

My issue is with a Netbeans 7.4 (also tried 7.3) project involving PHP and JavaScript where breakpoints do not work in jQuery ajax loaded pages that contain included JavaScript. I have no problem with PHP or top-level JavaScript, but for example: In index ...

Best practices for refreshing the HTML5 offline application cache

My website utilizes offline caching, and I have set up the following event handler to manage updates: applicationCache.addEventListener('updateready', function () { if (window.applicationCache.status == window.applicationCach ...

Can you outline the distinctions between React Native and React?

Recently delving into the world of React sparked my curiosity, leading me to wonder about the distinctions between React and React Native. Despite scouring Google for answers, I came up short on finding a comprehensive explanation. Both React and React N ...

I'm having trouble getting a http.request to run within an imported module. It just doesn't seem to work when I try to access

Here is the code from my main.js file: var spaceJson = require('./space.js'); var options = { "method": "GET", "hostname": "10.10.111.226", "port": null, "path": "/API/Org", "headers": { "authorization": "Bearer eyJ0eXAiOiJKV1QiLCJ ...

Using JSON data to populate the jQuery UI Datepicker

Is it possible to populate this jQuery UI datepicker calendar with data from a JSON file containing all non-working days for the years 2017 and 2018? P.S. return [!(month == 8 && day == 27), 'highlight', highlight]; - This example demons ...

The result from Axios yields an [object Promise]

Utilizing the Flickr API, I am receiving feed images from their platform. In my Vue application, I have a computed property called filteredImages: computed: { filteredImages: async function() { return axios.get('https://api.flickr.com/services/feed ...

Utilize Gson in Kotlin to Parse JSON with Nested Objects

I am attempting to transform the JSON below into a list data object: [ { "type": "PHOTO", "id": "pic1", "title": "Photo 1", "dataMap": {} }, { "type": ...

Wrapping an anchor tag with a div in Codeigniter

Can a div tag be used inside an anchor function? I have a div with the following CSS: #first{ opacity:0; } Now, I want to include it in my anchor element. Here is the code snippet: <?php if(is_array($databuku)){ echo '<ol>&l ...

Creating a Circle with Pixi.js v4 and Typerscript in IONIC 2

I have been attempting to create a custom class in TypeScript that utilizes PIXI.js to draw circles. Below is the code for my home.ts class: import { Component, ViewChild, ElementRef } from '@angular/core'; import { NavController } from 'i ...

Ways to retrieve accurate information from various arrays

I received the following results and I need to extract specific information such as service name, price, expected delivery date, etc. Can someone provide guidance on how to loop through the data and extract this information accurately? Thank you Arra ...

Displaying data from a remote JSON source in a Swift tableView

I am facing a challenge in populating a tableView with remote JSON data. The fetchRecentPosts method is responsible for fetching the data asynchronously, and it is called within the viewDidLoad method. However, the issue arises because the table view does ...

Rotate through different image sources using jQuery in a circular pattern

I'm working on a project where I have 3 img tags in my HTML file. My goal is to change the src of all 3 images with a button click, using an array that stores 9 different image src links. When the page initially loads, it should display the first set ...

Refresh the DATATABLE inside an AJAX call without reloading the entire page

I'm currently working with a table that utilizes the Datatable plugin. I have successfully implemented filtering and deletion functionality within the table. However, after deleting certain entries, I noticed an issue where the deleted item still app ...

Issue with hidden sourcemap not loading in Chrome or Firefox during Vite build

Transitioning my react application from create-react-app to Vite has resulted in some unexpected behavior with source maps. To learn more about Vite's documentation on source maps, click here. Initially, I was thinking of using sourcemap: true, but th ...

Searching with jQuery autocomplete and displaying the results within a div

I have recently started using jQuery Auto Complete for the first time and managed to get it working. However, I am now looking to make some edits but finding it a bit challenging. My goal is to utilize the auto complete feature to search through a product ...

Error encountered while executing ExpressJs function that was converted to a promise

Understanding how errors are handled in promises can be a bit tricky, especially for someone new to promises like myself. I'm trying to make the most of them, but I'm not quite there yet. Here is the code snippet I'm working with: app.list ...

Is there a way to use setTimeout in JavaScript to temporarily stop a map or loop over an array?

data.forEach((d, i) => { setTimeout(() => { drawCanvas(canvasRef, d); }, 1000 * i); }); I have implemented a loop on an array using forEach with a one-second delay. Now I am looking to incorporate a pause and resume f ...

Tips for achieving expansion of solely the clicked item and not the whole row

I am trying to create a card that contains a cocktail recipe. The card initially displays just the title, and when you click on a button, it should expand to show the full menu and description. The issue I'm facing is that when I click on one element, ...

Determine the element(s) that are the nearest to the mean value of the

Looking for a more 'ruby' way to solve this problem as I transition from imperative programming to Ruby. My goal is to find the element in an array that is closest in size to the average of the array. For example, let's consider the followin ...