Using javascript, retrieve the JSON values for each level

I need help using a recursive function in JavaScript to retrieve the last key value pair from a simple JSON object.

Here is an example JSON object:

{
  'a': {
    'b': {
      'c': 12,
      'd': 'Hello World'
    },
    'e': [1,2,3]
  }
}

The expected result should look like this:

{
  'a/b/c': 12,
  'a/b/d': 'Hello World',
  'a/e': [1,2,3]
}

This is the function I am currently trying to work with:

function getDeepKeys(obj) {
    var keys = [];
    for (var key in obj) {
        keys.push(key);
        if (typeof obj[key] === "object") {
            var subkeys = getDeepKeys(obj[key]);
            keys = keys.concat(subkeys.map(function (subkey) {
                return key + "/" + subkey;
            }));
        }
    }
    return keys;
} 

However, the output I am getting includes unexpected numbers like a/b/c/d/e/0/1/. Can anyone suggest a solution to fix this issue?

Answer №1

If you want to achieve this task iteratively, you can utilize an explicit stack approach. This method is more efficient than using recursion and prevents the risk of overflowing the call stack:

const pathify = object => {
  const paths = {};
  const stack = [[object, []]];
  
  while (stack.length) {
    const [current, path] = stack.pop();
    
    for (const key in current) {
      if (typeof current[key] === "object" && !Array.isArray(current[key])) {
        stack.push([current[key], path.concat(key)]);
      }
      else {
        paths[`${path.join("/")}/${key}`] = current[key];
      }
    }
  }
  
  return paths;
};

console.log(pathify({'a':{'b':{'c':12,'d':'Hello World'},'e':[1,2,3]}}));

Answer №2

It seems like you may be overcomplicating things unnecessarily. One way to approach this is by checking for an array using Array.isArray, and for a non-object (typeof !== 'object), then simply returning the path and its corresponding value. If it is not an array or a non-object, you can recursively iterate through each entry using reduce(). It's also helpful to pass the current path as an argument to the recursive function:

let sampleObj = {'a': {'b': {'c': 12,'d': 'Hello World'},'e': [1,2,3]}}

function retrieveValues(obj, path = []) {
    return (Array.isArray(obj) || typeof obj !== 'object')
    ? {[path.join('/')]: obj}
    : Object.entries(obj).reduce((acc, [key, val]) =>
        Object.assign(acc, retrieveValues(val, path.concat(key)) )
    , {})
}

console.log(retrieveValues(sampleObj))

Answer №3

To iterate over keys in objects and recursively navigate nested objects, you can utilize the Object.keys function.

let obj = {'a': {'b': {'c': 12,'d': 'Hello World'},'e': [1,2,3]}},
    result = Object.create(null),
    loop = function (o, arr, result) {
      Object.keys(o).forEach(k => {
        arr.push(k);
        if (typeof o[k] === 'object' && !Array.isArray(o[k])) loop(o[k], arr, result);
        else result[arr.join('/')] = o[k];        
        arr.splice(-1);
      });
    };    
    
loop(obj, [], result);
console.log(result);
.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

Tips on updating a JSON file exclusively using vanilla JavaScript with an AJAX call using the HTTP POST method?

Question One: I have been struggling to find a way to update a JSON file using the HTTP POST method when both files are stored on the same server (e.g. Godaddy or AWS). While I am able to send data to the server successfully, the JSON file is not being upd ...

What's the best way to refactor the `await nextEvent(element, 'mousemove')` pattern in my code once it is no longer necessary?

Within my React component, the code includes the following: class MyComponent extends React.Component { // ... trackStats = false componentDidMount() { this.monitorActivity() } componentWillUnmount() { this.trackStat ...

Transforming the "[myObject][1][application]" string into a valid path for a JObject

Let's begin by illustrating what I aim to achieve with pseudo code (even though this example is not feasible). var route = "[Info][Category]"; var document = callToDatabase(); var specificValue = document[route]; I am looking to transform a string i ...

The functionality of the jQuery function is disrupted when I navigate to a different page/row or perform a search for specific items

Recently, I created a JQuery function that deletes the selected row. Although I am aware of the DataTables option available for this purpose, I chose to implement it myself using just JQuery and JSON without relying on AJAX. However, a problem arises when ...

Posting JSON data in MVC4 to upload a large amount of data into the database

When I upload Bulk Entries in my Database using JSON, I encounter a problem with the last table column as it is showing null entries. Below are my controller model and JSON data. What could be wrong with this code? This is my Controller public void ESBul ...

The act of exporting components from the main index file allows for

I have assigned a components folder where I created various components that I want to export to the index.js file and then export all of them from there. This is an example from one of the components files: export default ToggleSwitch; Now, in the inde ...

The button labeled "issett" is malfunctioning

Hey there, so I've created a registration form using jQuery and PHP that validates user input in real-time as they type. Once all the information is correct, I want to allow the user to submit the form. My plan is to write an if statement that checks ...

Obtaining a JSON reply using Ember

Exploring new possibilities with Ember js, I am eager to switch from fixtures to using an API. Below is the code I have implemented to fetch the data: App.ItemsRoute = Ember.Route.extend({ model: function() { return $.getJSON('http://som ...

Is Socket.io combined with Redis the best architecture for an interactive gaming experience?

My current setup involves a NodeJS scaling architecture with Redis, specifically designed for a real-time multiplayer game. However, I'm facing challenges in configuring separate lobbies for players, as the load balancer assigns users to different ser ...

Increase the Z-Index of the Header above the Material UI Modal Background

Currently, I'm in the process of developing a mobile version of a web application using Material UI. However, I am encountering some challenges when it comes to matching the designs accurately. My approach involves utilizing the MUI App-Bar in conjunc ...

Is the RouterModule exclusively necessary for route declarations?

The Angular Material Documentation center's component-category-list imports the RouterModule, yet it does not define any routes or reexport the RouterModule. Is there a necessity for importing the RouterModule in this scenario? ...

Eliminate specific content from within a div tag

Looking for a solution with the following HTML. <div id="textDiv"> <p> MonkeyDonkey is not a bird. Monkey is an animal. </p> </div> In this case, I am trying to delete the word "Donkey". I attempted the code below but it did no ...

Is there a way to have the collapsible content automatically expanded upon loading?

I came across a tutorial on w3school (https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_collapsible_symbol), which demonstrates collapsible content hidden by default. The code snippet from the link is provided below. Can someone assist me in cha ...

Rotating arrows enhance the functionality of the accordion menu

I have successfully implemented a basic accordion with rotating arrows on click. Everything is working smoothly except for one issue: When I collapse one item and then try to collapse another, the previous arrow does not return to its default state. Is ...

Serializing a Map containing key-value pairs represented as a case class using circe

Here is a simplified code snippet that involves a Map with key and value as case classes. The key and value objects are successfully serialized using circe. However, there is a challenge in serializing Map[CaseClassKey, CaseClassValue] with circe. //////de ...

Using Ionic to invoke a function within another function in a JavaScript service

Hey everyone, I've come across an issue while working on my Ionic mobile app project. I need to call a function within another function in one of my service.js files (pushNotificationService.js). Here is the code snippet: checkForNewMessage: functi ...

Display a bootstrap toast using a JavaScript class method

One way to display a bootstrap toast is by using the following code snippet: let my_toast = new myToast('title', 'hello world'); my_toast.show(); Currently, I am loading the HTML content from an external file named myToast.html: < ...

Automatic Refresh and Search Functionality on PHP Page

Can anyone help with a problem I'm having trying to implement auto-reload on a page with a table in the form of rows that contain usernames? I am currently using the jQuery searchable plugin from here to search for usernames within the div. The websi ...

Encountering a 404 error with Angular 6 routing after refreshing the page when using an Nginx proxy

I currently have my angular application running within a docker container, exposed on port 83. Additionally, I have a separate spring-boot rest app running inside another docker container, exposed on port 8083. On the host server, there is an Nginx server ...

Anomaly in Date String Comparison within Angular Controller

Having a puzzling issue when attempting to compare two date strings within my Angular Controller. It seems that the comparison is yielding unexpected results. To explain, I first convert today's date to a string ("2/5/2016") and then proceed to use it ...