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

Exchange selection choices among harvested selected boxes

In my project, I am working on swapping all the options between two select boxes. The specific scenario I am dealing with involves recording details of phone calls. These calls can either be inbound or outbound. For outbound calls, I have a 'caller&ap ...

Reactjs Invariant Violation caused by the npm package (react-loader)

I'm currently attempting to integrate react-loader into my react component. This is the code snippet I'm using: /** @jsx React.DOM */ var Loader = require('react-loader'); var DisplayController = React.createClass({ // etc ...

The name field in the request body is currently undefined

Currently, I am working on developing a basic blog page using technologies such as ejs, JavaScript, Node.js, Express, and body-parser. While working on passing inputs to the command line, specifically for the title, I encountered an issue. When I used req ...

What is the best approach to extracting tightly-coupled code and converting it into an external library?

I have a question regarding paradigms that I would like to address, and if this is not the appropriate platform, please guide me to the right place. Your recommendations are most welcome :) Currently, I am tasked with extracting a significant piece of fun ...

"Embedding a Highcharts web chart within a pop-up modal window

I am looking to incorporate a Highcharts web chart onto a specific part of a Bootstrap modal, while ensuring the size remains dynamic along with the modal itself. Here's what I have attempted so far: Sample HTML code: <td><a href="#">${ ...

Getting to a nested key in a JSON object with JavaScript: a step-by-step guide

Currently, I'm working with a JSON file and need to extract the fileName tag for use. { "dataset": { "private": false, "stdyDscr": { "citation": { "titlStmt": { "titl": "Smoke test", "IDNo": ...

Handling Posts and Gets with Jquery/Javascript

Working on a web application that involves generating numerous post and get requests. I am able to monitor all the requests using Developer Tools in Mozilla/Chrome, as well as with Charles (an app). Is it feasible to develop a jQuery or JavaScript functi ...

Having trouble passing a token for authentication in Socket.IO v1.0.x?

I am currently following a tutorial on creating a token-based authentication system, which can be found here. I have implemented the following code: Code in app.html: var socket = io('', { query: "token=i271az2Z0PMjhd6w0rX019g0iS7c2q4R" }); ...

How to change elements within an HTML string using jQuery

I am facing an issue where I have an HTML string (not DOM) that needs to be manipulated using jQuery. However, the code I am trying does not seem to work as expected: var html = '<div><h4><a class="preview-target" href="content.html"&g ...

Storing results of calculations in a database when there is a significant imbalance between the frequency of reads and

Currently, I am facing a dilemma that requires expertise beyond my own. I am seeking assistance in this matter. I have developed an efficient query for retrieving table data along with linked data, without getting into specifics about the content itself. ...

Exploring SVG Morphing Reversal Techniques in Anime.js

I have been trying to implement direction: 'reverse' and timeline.reverse(), but so far it hasn't been successful. Interestingly, when I set loop: true, the reverse animation can be seen within the loop. However, my goal is to trigger this a ...

Customize your select element's background using jQuery when the content changes

Here is a select element with different options to choose from: <select class="state"> <option value="1">Done</option> <option value="2">Closed</option> <option value="2">Open</option> <option v ...

Use CSS media queries to swap out the map for an embedded image

Looking to make a change on my index page - swapping out a long Google Map for an embedded image version on mobile. The map displays fine on desktop, but on mobile it's too lengthy and makes scrolling difficult. I already adjusted the JS setting to "s ...

eliminate the use of RelativeLayout in the Java code

In my project, I am facing an issue with utilizing web services. I encounter a scenario where the JSON web service returns nothing, and in such cases, I want to remove the relative layout that I have defined in my code. The layout consists of three relativ ...

The WordPress database supports JSON formatting for data storage

I am facing an issue with importing JSON data into a WordPress database. The correct table has been identified, but the example JSON data in the table is not in a standard JSON format. The JSON data I need to import is: {"name": "John","last_name": "Doe"} ...

The sequence of execution in React hooks with Typescript

I'm having difficulty implementing a language switching feature. On the home page of my app located at /, it should retrieve a previously set preference from localStorage called 'preferredLanguage'. If no preference is found, it should defau ...

Embracing async-await while awaiting events in node.js

I am attempting to incorporate async await into a project that is event-driven, but encountering an error. The specific error message I am receiving is: tmpFile = await readFileAsync('tmp.png'); ^^^^^^^^^^^^^ SyntaxError: Unexpec ...

Testing a React component that uses useParams: A step-by-step guide

I've been working on creating a BBS App using TypeScript, React, React Router, and React Testing Library. However, I've encountered an issue where a component utilizing useParams is not passing a test. Interestingly, it seems to be working correc ...

Discover the best method for summing all values within a JSON object that contains multiple unique keys

What is the best way to sum up all values in a JSON object? The object provided below contains values that are in string format and it has different keys. var numbers = { x: "4", y: "6", z: "2" }; The result should be: total ...

Issue encountered while integrating Angular with Grails

Below is the content of my index.gsp file <!DOCTYPE html> <html ng-app="myApp"> <head> <title>my app</title> </head> <body> <input type="text" data-ng-model="test"/> {{test}} </body> <script src ...