Exploring the power of JSON through recursive techniques

Greetings, I'm relatively new to the concept of recursion and it has been some time since I last worked with it, so please forgive me if my question appears a bit basic. Essentially, I have a JSON structure similar to this:

  {
   "id": "1111",
   "name": "Outdoor Skiing",
   "parent_id": "1110",
   "parents": [
     {
        "id": "1000000",
        "name": "Movies"
     },
     {
        "id": "1000001",
        "name": "Outdoor Movies"
     }
   ]
 }

I am looking to reorganize it into the following format:

{
  "id":"1000000",
  "name":"Movies",
  "children":[
     {
       "id":"1000001",
       "name":"Outdoor Movies",
       "children":[
          {
            "id":"1111",
            "name":"Outdoor Skiing",
            "parent_id":"1110",
            "parents: [....these can stay here....]
          }
       ]
     }
  ]
}

Would greatly appreciate any assistance on how to achieve this using recursion. Thank you!

Answer №1

If you're open to using underscore, this might be the solution you've been searching for:

function flipObject(obj, newObj, offset) {
    offset ? offset++ : offset = 1;
    var newParent = _.first(_.last(obj.parents, offset));
    newObj ? newParent.children = newObj : newParent.children = obj;
    if (offset < _.size(obj.parents))
    {
        flipObject(obj, newParent, offset);
        return;
    }
    // the 'newParent' variable now holds the desired object
};

Check out this JSFiddle demo

Edit: As requested by many, here's an alternative example without using underscore - click here.

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

Is it possible to selectively export certain interfaces within a .d.ts file?

// configuration.d.ts export interface Configuration { MENU_STRUCTURE: Node[]; } interface Node { name: string; } Looking at the snippet above, I am aiming to only export Configuration. However, I noticed that I can also import Node from an ext ...

Is there a way to ensure that an external file function completes before proceeding with the main code execution?

In my project, I have two key JavaScript files: main.js and load.js. Within load.js, there are two essential functions - getData, which makes an AJAX post call, and constHTML, which appends data based on the JSON array returned from the AJAX call. This app ...

Make sure to wait for the loop to complete before moving on to the next line

I am currently leveraging the capabilities of the GitHub API to fetch a list of repositories. Subsequently, I iterate over each repository and initiate another HTTP request to obtain the most recent commit date. How can I orchestrate the iteration process ...

Implementing key strokes in an HTML input field within a geckoWebBrowser

I am currently using the "geckoWebBrowser1" component to navigate to a URL that displays a login textbox with the ID: login-email Although I have successfully inserted "[email protected]" into the aforementioned textbox, it is essential to simulate k ...

Res.end isn't halting the script's execution process

I'm currently facing an issue while building an API around a third-party API in my Express route. The problem is that the script keeps executing even after encountering a 406 error. Below is the snippet of my code: app.get('/submit/:imei', a ...

On Windows systems, where exactly does npm place its packages during installation when using Node version 10.x

Does anyone know where I can locate the locally installed npm modules when using NodeJS version 10? I have checked under C:\Users\MyUser\AppData\Roaming, but I cannot find the "npm" folder. ...

What is the process for incorporating a resource into a bundle with the fhirclient library (Smart on FHIR)?

Recently, I've been utilizing the fhirclient (Smart on FHIR) python library to work with bundles and individual resources. However, I'm facing a challenge in figuring out how to add a resource to a bundle using helper methods within the "Bundle" ...

Is the bearer terminology used for the authentication token or is it meant for a separate token?

In my MEVN application, I am incorporating JWT tokens and currently exploring how to transmit authentication tokens via axios. It is common practice to add "Bearer " before the token and have the server strip off "Bearer " to access the token's conten ...

Is there a way to differentiate between a preflight request and the actual request?

Currently, I am utilizing CORS to transmit data to a server located on a different domain. Initially, the browser dispatches the preflight request to verify the server, followed by the main request. My goal is to identify when the request is in the "prefl ...

Using Flask to send and receive JSON requests with boolean values

How can I include a boolean value in the request body using the Python requests library? I attempted: request_body = {'someBooleanValue': true}. => NameError: name 'true' is not defined request_body = {'someBooleanValue': ...

Retrieve data from HTML Form arrays using JavaScript

I have a situation in my forms where arrays are being sent back in the following format: <input class="checkbox-service" name="services['electricity']" type="checkbox"> <input class="checkbox-service" name="services['water'] ...

Change request.js to axios for utilizing the Vonage API

I have been developing a messaging project using the Vonage API. The current code is functioning properly, but I am attempting to switch it to using axios instead of require.js var request = require("request"); const data = JSON.stringify({ fro ...

Internet Explorer 11's readyState is consistently 'loading' and the DOMContentLoaded event is not firing because of non-SSL content

When using IE11 and encountering the user prompt Only secure content is displayed. #Show all content# The readyState remains constant at loading and the events do not trigger. Everything works fine once the user clicks on Show all content. Unfortu ...

Is it possible to implement sticky sessions with Node.js and pm2?

Can sticky sessions be implemented using the pm2 node module? Although not supported by Node.js's internal cluster module on purpose, it could still prove beneficial in scenarios like paused media streams. ...

Navigating between two table components in React JS

I am a beginner in the world of React and I am struggling with switching between these two tables. Despite consulting the documentation for inline conditional statements, I still couldn't figure it out. My goal is to have the tables switch after click ...

Generate several sliders using JQuery effortlessly

As I was attempting to create multiple sliders with JQuery in a more automated fashion using iteration, several questions arose (you can see a functional example below). Why does the first block of JQuery code work while the second block of JavaScript cod ...

Utilizing promise values within asynchronous functions

I know this question has been asked multiple times, but I'm facing a situation where I need to retrieve a variable created within a promise. The examples I've come across involve using .then to access the data, but in my case, I need to work with ...

Having trouble with the installation of react-burger-menu

While attempting to install the react-burger-menu library on a React project using npm install react-burger --save, I encountered an error that is preventing me from progressing with my project: npm ERR! While resolving: MYPROJECT npm ERR! Found: [email&# ...

Comparing OpenCPU and jsonlite: Utilizing column-based "/json" format versus row-based approach

Is there a way to modify the default "/json" suffix option on data.frames in R to be column-oriented rather than row-based? Data.frames in R essentially function as named lists with equal-length components. Using the jsonlite package, we can easily illust ...

Duplicating an element in an array using JavaScript

My view model is structured as follows public class ItemViewModel { [Required] public int Id { get; set; } [Required] public int JobId { get; set; } public string ItemId { get; set; } public string ItemN ...