Learn how to locate the JSON path for a particular value by utilizing JavaScript

Can anyone assist with finding the JSON path for a specific value using Javascript?

var data = {
    key1: {
        children: {
            key2:'value',
            key3:'value',
            key4: value
        }, 
    key5: 'value'
}

The expected result from the above code would be data.key1.children.key3

Any assistance on this matter would be greatly appreciated.

Answer №1

let variable = "value3"; information["value1"]["children"][variable];

Answer №2

This particular method is designed to extract all potential pathways within an object: By making use of this approach, you will receive a list of potential paths that look like

["key1.children.key2", "key1.children.key3", "key1.children.key4", "key1.key5"]

function gatherPaths(base) {
  let stack = [];
  let result = [];

  // Checking for object type
  const checkObject = value => typeof value === "object";

  stack.push(base);
  while (stack.length > 0) {
    let currentNode = stack.pop();
    if (checkObject(currentNode)) {
      Object.entries(currentNode).forEach(([childNodeKey, childNodeValue]) => {
        if (checkObject(childNodeValue)) {
          const newObj = Object.fromEntries(
            Object.entries(childNodeValue).map(([cnk, cnv]) => {
              return [`${childNodeKey}.${cnk}`, cnv];
            })
          );
          stack.push(newObj);
        } else {
          stack.push(`${childNodeKey}`);
        }
      })
    } else {
      result.push(currentNode);
    }
  }
  return result.reverse();
}

Feel free to drop a comment if you found this function useful!

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

Dynamic content for tooltips in Angular

Currently, I am facing a challenge where I need to dynamically populate content in a tooltip by executing a function with a parameter. This parameter holds the crucial information required to update the tooltip content. The complexity arises from the fact ...

Different component instance captures the EventEmitter from a component inside ng-template

After developing a component with an event, let's refer to it as (onAction). This component is utilized in two different places within the same parent component or page, both of which are individual components themselves. The only variation between th ...

Retrieve the value of a dropdown menu by referencing its name in JQuery

My webpage contains the following dropdowns: <select id="select_status_id44" name="select_status_id[44]" class="inputbox" id = "status_id_44"> <option value="1">Pending</option> <option value="2" selected="selected">Confirmed& ...

Utilizing PHP and Ajax for paginating JSON responses

I have successfully parsed some JSON data from the YouTube API, but I am running into a limitation where only 50 results can be shown per request. I am looking for help on how to implement pagination using either JavaScript or Ajax in my PHP script. The go ...

Google Maps Circle Radius Functionality Malfunctioning

I've been trying to implement a map scaling feature using a slider in my code but I'm having trouble getting it to work. While the map is displaying correctly, the radius won't update as intended. Any assistance with this would be greatly ap ...

Alter the content of a div depending on the values of three different elements

Hello everyone, I am new to the world of jQuery and javascript, and I am facing a challenge that I need some help with. Within a form, there are two fields that I would like to perform calculations on. Here is what I have attempted so far: jQuery.fn.calcu ...

What is the best way to generate an extensive table with HTML and AngularJS?

I am looking to implement an expandable table feature where a single header with a plus icon can be clicked to reveal the child rows beneath it. Currently, I have been able to achieve this functionality. However, I am facing an issue where the child rows ...

What is the best way to combine key and value back into an object?

Within my Angular application, I am utilizing ng-repeat to iterate through all the elements in a JSON object. For instance, consider the following JSON structure: $scope.animals = { horse: { sound: "Nay", legs: 4, } bea ...

What is the process for running "node server.js" within codelab?

I am currently going through a codelab tutorial on Bitbucket at this link After installing node.js for the first time, I encountered an error when trying to run the server.js file: node server.js The error message "node: Command not found" appeared even ...

The JavaScript file specified in the script tag's src attribute was successfully downloaded, but it did not execute as expected after being fetched

I've implemented an ajax call using jQuery in the following manner: $.ajax({ type: 'GET', url: 'edit.htm', success: function(data){ container.html(data); }, }); After making the ajax call, the data returned includes s ...

Techniques for retrieving elements from HTML using jQuery

I'm developing a feature that allows users to add videos to playlists by clicking on a link in a popover. The challenge I'm facing is extracting the video_id and the selected playlist when the user interacts with the popover. Any tips on how to a ...

EJS files do not show variables passed from Node

I am currently developing a 'preferences' section on my website, where users can make changes to their email addresses and passwords. Within this preferences page, I aim to showcase the user's current email address. router.get("/settings", ...

Retrieve the title of an item stored within a list

Let's say I have an array filled with objects - exactly 10 of them, each with unique names. var upgrades = [ tree = {price: 20, rate:0.5, owned:0}, irr = {price: 80, rate:1, owned:0}, press = {price: 150, rate:2, owned:0}, cracker = {price: 400, rate ...

The functionality of sending a list of objects with a file via AJAX to an ASP.NET controller is failing to

Currently, I am working on ASP.NET Core and I need to send a list of objects containing files from an Ajax request to the controller. For more details, the object I want to send includes a file. You can view an image here. ViewModel public class FormDat ...

Guide to activating a function by tapping anywhere on a webpage in iPhone Safari

I am attempting to implement a jQuery function that will change the text of a div in the iPhone browser when any area of the page is clicked. Here is my current setup: <div id="alternative_text">traduit</div> <script type="text/javascript ...

What is the best way for me to incorporate images retrieved from an API call into my

Hey everyone, this is my first time posting on here so if there's anything I'm missing, please let me know! I've run into an issue with the images on my categories page not aligning properly and being different sizes after I incorporated som ...

Is there a way to verify whether a character in a string is already present in an array as an element?

Given a string, for example: data, I am looking to extract all new characters and store them in an array. Following the provided example, the desired output should be: characters = ["d","a","t"]; My current approach is as follows: const balanced = string ...

Sequencing Jquery scripts within an ASP.NET MVC 4 framework

In my ASPNET MVC 4 project with jqgrid, I have encountered a dilemma. By default, ASPNET MVC 4 places the '@Scripts.Render("~/bundles/jquery")' code at the end of the _Layout.cshtml file. However, in my Index.cshtml file where I am using jqgrid, ...

Encountered issues retrieving data using a combination of Docker, MySQL, Express, and TypeScript

After successfully creating a todo-app using Node.js, TypeScript, and MySQL, I encountered an error when trying to run the app on a Docker Container. Failed to load resource: net::ERR_NAME_NOT_RESOLVED TypeError: Failed to fetch at getTodos (ListTodo.t ...

Execute an AJAX call to remove a comment

Having some trouble deleting a MySQL record using JavaScript. Here is the JavaScript function I am trying to use: function deletePost(id){ if(confirm('Are you sure?')){ $('#comment_'+id).hide(); http.open("get","/i ...