Transform JavaScript object into desired structure

let obj = {
    "rec": [{
            "id": "25837",
            "contentId": "25838"
        },
        {
            "id": "25839",
            "contentId": "25838"
        },
        {
            "id": "25838"
        },
        {
            "id": "25636",
            "contentId": "25837"
        }, {
            "id": "25640",
            "contentId": "25839"
        }
    ]
};

I am working with a JavaScript object that requires manipulation to achieve the desired format.

{
    "children": [{
        "id": "25838",
        "children": [{
                "id": "25837",
                "contentId": "25838",
                "children": [{
                    "id": "25636",
                    "contentId": "25837"
                }]
            },
            {
                "id": "25839",
                "contentId": "25838",
                "children": [{
                    "id": "25640",
                    "contentId": "25839"
                }]
            }
        ]
    }]
}

If an object does not have a contentId, it should be at the parent level. Subsequently, objects with a contentId matching the parent id should be placed at its child level and so on.

I have set up a demo in this fiddle here, but I need help completing the logic. Do you have any ideas or references to help me achieve this?

Answer №1

To achieve the desired outcome, you can implement a recursive function using the reduce method.

let data = {"rec":[{"id":"25837","contentId":"25838"},{"id":"25839","contentId":"25838"},{"id":"25838"},{"id":"25636","contentId":"25837"},{"id":"25640","contentId":"25839"}]}

function nest(data, pid) {
  return data.reduce((r, e) => {
    if (pid == e.contentId) {
      const obj = { ...e }
      const children = nest(data, e.id);
      if (children.length) obj.children = children
      r.push(obj)
    }

    return r;
  }, [])
}

const result = nest(data.rec);
console.log(result[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

What is the best way to send data from ajax to a django view?

I have a script for ajax that retrieves the public key and sends other details to the Stripe server for payment. However, I am struggling with sending the dynamic value of the price to item_line. fetch("/config/") .then((result) => { return re ...

Error encountered in Angular Html2Pdf: Unable to assign the 'adoptedStyleSheets' attribute on 'ShadowRoot' due to DOMException

Looking for assistance in implementing html2pdf with Angular 12 to convert specific parts of an HTML page into a downloadable PDF. ERROR MESSAGE An error occurred while trying to execute the code: index-7a8b7a1c.js:150 Uncaught (in promise) DOMExce ...

What are some ways to maintain consistent audio levels on a jquery volume slider?

My html5 webpage features a slider and an audio track, but I am not using the sound tag property controls="controls". I want the slider to control the volume of the audio file. When I include the following code in the body tags, everything works perfectly: ...

Retrieve the initial value of the input element following a modification

Is there a way to retrieve the original default value of an input field after changing it using .val()? In my HTML, I have various text-inputs with classes .large and .medium, each with its own default text value. What I'm trying to achieve is when a ...

Exploring the power of Typescript functions within a traditional VueJS project

TL;DR: How can I import and use a typescript module into my plain js Vue-Components? I have a Vue 2 (not yet 3) project. In this specific project, I have made the decision to refactor some of the code logic into ES modules for improved testability and reu ...

Top method for directly converting SVG to JSX within a popular React component library

Currently, I am exploring the most effective method to directly import SVG images as JSX components into my React common component library. By "common component library," I am referring to a distinct package that houses shared components utilized by variou ...

The data type 'string' cannot be assigned to the type '(url: string) => string'.ts(2322)

I am working with a Material UI copyright component: export default function Copyright(link: string, text: string) { return ( <Typography variant="body2" color="textSecondary" align="center"> {'Copyright © '} <Link co ...

Creating various functions for Joomla's AJAX component development

My component is currently working smoothly with AJAX and mootools. The view.raw.php file contains only one function called display. I've been attempting to add other functions within the component that can be accessed through AJAX, but have been facin ...

Utilizing Jquery's .GET method to retrieve and handle JSON data

In the jQuery snippet below, I am trying to fetch product data from . However, I am facing difficulty in iterating through the loop to access all 30 products along with their details. $.get("https://dummyjson.com/products/1") .done(function ...

Condition in SQL for searching full name with no specific order of first name or last name

How can I search for a column named fullname by filtering on firstname/lastname without specific order? In the following Javascript example, the query is invalid when searching by lastname: function getQuery(searchWord){ return `SELECT * FROM user WHERE ...

transferring various data from JavaScript page to PHP page

Is it possible to pass multiple values from a service page to a PHP page? I am trying to pass the values 'data', 'albimg' and 'albvideo' to the PHP page, but I keep encountering an error. Please refer to the image below for mo ...

Strategies for avoiding unused style tags in React components

Expanding beyond React, I'm unsure if React itself is the culprit of this issue. In a React environment with TypeScript, I utilize CSS imports in component files to have specific stylesheets for each component. I assumed these styles would only be ad ...

Each time the server restarts, Express.js will run a function asynchronously

Looking for guidance on implementing a function in my Express.js app that can fetch data from the database and then cache it into Redis. The goal is to have this function executed only upon restarting the Web server. Any suggestions on how I can achieve t ...

jQuery: Implementing smooth horizontal scrolling functionality

Here is the code I am working with: // General Function $("li a").click(function() { $("li a").removeClass("active"); $(this).addClass("active"); }); // Horizontal Scroll-to Function $("li a").click(function() { var offset = this.getBounding ...

Root location for offline and pre-production in the Backbone boilerplate router

I am currently utilizing the backbone boilerplate found at https://github.com/tbranyen/backbone-boilerplate My development process involves working on static HTML/JS files offline and conducting tests offline before deploying them to another site for pre- ...

The "angular2-image-upload" npm package encountering a CORS issue

Using the angular2-image-upload library for uploading files has been a smooth process until recently. After upgrading from version 0.6.6 to 1.0.0-rc.1 to access new features in future, I encountered issues with image uploads. The errors I faced were: htt ...

What is the most efficient way to calculate the total sum of all product amounts without using Jquery?

I am working with a dynamic table where data is inserted and the total of each product is calculated by multiplying the price by the quantity. What I need now is to get the sum of all the totals for each product. You can see how the table looks here: htt ...

Tips for triggering onclick before changing to a new page?

Currently, I am developing a React application and have encountered the following situation: <a href={link} variant="primary" onClick={this.onClickDoSomething}> here. </a> My goal is for the onClick event to trig ...

Executing Selenium tests: utilizing the webdriver.wait function to repeatedly call a promise

Currently, I am using Selenium ChromeDriver, Node.js, and Mocha for testing purposes... I am facing a dilemma at the moment: The driver.wait function seamlessly integrates with until. I have a promise, which we'll refer to as promiseA. This pro ...

Adjusting color with the .on method in Event Listener

What's wrong with this code? html <!DOCTYPE html> <html> <head> <title>Ending Project</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> &l ...