Discover the "route" of a JSON element using JavaScript

I've been struggling to retrieve the "path" of a specific AngularJS scope variable. My end goal is to utilize this "path" as the ng-model for dynamically generated forms.

Below is my current code:

my_code.js:

var my_data = {
  name: "fred",
  number: 1,
  children: [
    { name: "bob" },
    { name: "joe" },
    { name: "norman" },
  ]
};

function get_path(obj, target, path) {

  if (typeof path === "undefined" || path === null) { 
    path = "my_data";
  }

  for (var key in obj) {
    var value = obj[key];
    var value_type = value.constructor;

    /* value can either be an Array */
    if (value_type === Array) {
      for (var i=0; i<value.length; i++) {
        if (value[i] === target) {
          return path + "." + key + "[" + i + "]";
        }        
        var result = get_path(value, target, path + "." + key + "[" + i + "]");  
        if (result) {
          return result;
        }
      }
    }

    /* or an Object (dictionary) itself */
    else if (value_type === Object) {
      var result = get_path(value, target, path + "." + key);
      if (result) {
        return result;
      }
    }

    /* or something atomic (string, number, etc.) */
    else {
      if (value === target) {
        return path + "." + key;
      }
    }  
  }
  return false;
}

When I pass the object my_data.children[0].name into this function, I anticipate receiving the string "my_data.children[0].name". However, it returns "my_data.children[0].0.name" instead. Can anyone pinpoint where I might be making a mistake?

P.S. - The initial inspiration for this solution came from Javascript/JSON get path to given subnode?, although it didn't account for Arrays.

Answer №1

Your mistake seems to be located here:

else if (value_type === Object) {

      var new_result = get_path(value, target, path + "." + key);
      if (new_result) {
        return new_result;
      }
    }

You mistakenly added "+ key" after the path. Simply remove it to fix the issue:

else if (value_type === Object) {

      var new_result = get_path(value, target, path);
      if (new_result) {
        return new_result;
      }
    }

Answer №2

@min-hong-tan successfully resolved the issue and deserves to be acknowledged as the accepted answer. Additionally, I have included the following code snippet for thoroughness:

if (value === target) {
  return path + "." + key;
}

This segment of code is added after each if block to account for scenarios where matching an entire Array (such as my_data.children) or an entire Object that is not part of an Array might be necessary.

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

How can you run a function in JavaScript or TypeScript that is stored as a string?

Is there a way to call a function that is stored as a string? For example: var dynamicFun = `function Hello(person) { return 'Hello' + person; }` In this case, the dynamicFun variable can store any function definition dynamically, such as: var ...

Design my div layout to resemble a tree shape

Take a look at this URL. I have dynamically created divs in a nested structure for a sports tournament. I need help styling the divs to match the tournament structure. This is how I want my structure to look. The code is functioning properly, it's ju ...

Struggling to get the AJAX code functioning correctly

Embarking on my journey with AJAX, I decided to test a simple example from the Microsoft 70515 book. Surprisingly, the code doesn't seem to be functioning as expected and I'm at a loss trying to figure out why - everything appears to be in order. ...

The template in AngularJS route fails to display

I am currently facing an issue with loading multiple pages using AngularJS $routeProvider and two controllers. Whenever I click on a link from the first partial to go to the second one, the second partial fails to render properly, displaying only template ...

Is there a way to resolve this issue? (An error occurred: TypeError - res.json is not a valid function)

When attempting to add an object to my MongoDB database const response = await fetch("/api/contact", { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json", }, }); I encounter the error message ...

Error: Reading the property 'any' of an undefined object resulted in a TypeError after an update operation

After updating multiple npm packages in my application, I encountered a series of errors that I managed to resolve, except for one persistent issue! TypeError: Cannot read property 'any' of undefined at Object.<anonymous> (/home/cpt/Deskto ...

Retrieve data from a URL using Angular 6's HTTP POST method

UPDATE: Replaced res.json(data) with res.send(data) I am currently working on a web application using Angular 6 and NodeJS. My goal is to download a file through an HTTP POST request. The process involves sending a request to the server by calling a func ...

Function does not reflect changes in an AngularJS directive model

I have created a custom directive as shown below: .directive("datepicker", function () { return { restrict: 'E', scope: { date: '=', filterfnc: '&' }, replace: t ...

Error encountered during the building of a Java project using Gradle

I ran into an issue with Git Bash error output (build failed). Despite attempting to resolve it by installing Python as suggested, setting the Python environment variable in IntelliJ, and following other recommendations, I still encounter the same build ...

Developing an Android app that utilizes a JSON HTTP API

Currently, I am in the process of developing an Android application that interacts with a JSON API and displays the results in a simple ListView. While referencing this tutorial, I initially copied their code to use as a foundation for my project. However, ...

Tips on incorporating "get_template_directory_uri" into a JavaScript function

I am currently working on my WordPress PHP file code, where I have included a JavaScript snippet to display names and images from a query. While the names are being displayed correctly, I am encountering an issue with the images not showing up. After tryi ...

What causes the picturesArray to remain consistently void?

const fetch = require("node-fetch"); let images = []; fetch('http://www.vorohome.com//images/assets/159314_887955.png') .then(response => response.buffer()) .then(buffer => { const data = "data:" + response.headers.get ...

Grin schedule module JSON stream

I have integrated a Smile timeline widget on my website and successfully customized it following several tutorials. However, I am struggling to utilize a Json service instead of relying on data stored in a global variable within a JavaScript file. Despite ...

Ways to display or conceal various divs by employing an if/else statement?

I am aiming to conditionally display various divs based on certain criteria: Show the "x" div if it's not already visible Display the "y" div only if the "x" div is already being displayed Show the "z" div only if both the "x" and "y" divs are alrea ...

Delving into the World of CSS

I have been working on changing the background image using this JavaScript code, but I am not sure what to reference in the CSS file. Despite reading through everything, my screen still remains blank. $(function() { var body = $('body'); var bac ...

What is the best way to access the value of an HTML tag in React?

Currently in the process of developing a feature for the price tab using React. These components are designed to allow users to add price classes to their shopping cart. One challenge I'm facing is how to retrieve the HTML string of an HTML tag. Here& ...

Using AngularJS's ng-repeat directive to convert expressions into JavaScript code

I am successfully retrieving data from my Database using AngularJS, however, I am struggling to find a way to extract the data from ng-repeat and store it in a JavaScript Object. Is the data treated as an expression after ng-repeat is applied? I have hear ...

Exploring the Depths of Mongo and MySQL: Advanced Querying

I'm currently working on a project and I'm trying to decide between using MongoDB or MySQL for storing the content. I have around 2000 pieces of content in my database, each with various metadata such as id, name, type, tags, color, date, views, ...

Python - Extracting page ID from JSON data

{"query":{"normalized":[{"from":"hijab","to":"Hijab"}],"pages":{"68301":{ When working in a Linux environment using Python: >>> data['query']['pages'] {u'68301': {u'extract': u'<p/>"</b>Hi ...

Contentful integrated into a NuxtJs website

After successfully creating a blog using Nuxt JS and integrating Contentful into the project, I followed a helpful tutorial from here. This enabled me to retrieve all sections such as title, date, and content of the post efficiently. However, I am current ...