Transform data dynamically into tree-like structure in JavaScript

I am working with an array of actors, each of whom have arrays such as movies, awards, and more. I need to restructure the data received from the server into a tree format. The name of each array should be placed in a new array called children, which includes 3 properties: a unique id, the array name (e.g., 'movies'), and the actual data within that array. I require assistance in dynamically creating this structure to accommodate potential data expansion. Any guidance would be greatly appreciated.

Here is the initial data structure from the server:

[{
    name: 'Tom Holland',
    id: 1,
    movies: [{
      typename: 'MoviesData',
      id: 12,
      name: 'Spider-Man NWH',
      stars: 4
    }, {
      typename: 'MoviesData',
      id: 13,
      name: 'Spider-Man Far from Home',
      stars: 4
    }],
    awards: [{
      typename: 'AwardsData',
      id: 6,
      name: 'BAFTA Award',
      year: 2017
    }, {
      typename: 'AwardsData',
      id: 7,
      name: 'Empire Award',
      year: 2013
    }]
    //...additional arrays like Hobbies, TV-Shows, etc.
  }
  //...more Actors
]

This is the desired tree data structure:

[{
    name: "Tom Holland",
    id: 1,
    children: [{
        id: 3, // generated id for each array
        name: "Movies", 
        children: [
          {typename: 'MoviesData', id: 12, name: 'Spider-Man NWH', stars: 4},
          {typename: 'MoviesData', id: 13, name: 'Spider-Man Far from Home', stars: 4}
                   // additional movies...
                   ]
    }, {
        id: 15, // generated id
        name: "Awards",
        children: [
          {typename:'AwardsData', id: 6, name: 'BAFTA Award', year: 2017},
          {typename:'AwardsData', id: 7, name: 'Empire Award', value: 2013}
                   // additional awards...
            ]
    }, //...]
  }, //...]

Answer â„–1

Outlined below is a potential approach to accomplish the specified goal.

Code Sample

const transformData = arr => (
  arr.map(
    ({name, id, ...rest}) => ({
      name, id,
      children: [
        ...Object.entries(rest)
        .map(([key, value], idx) => ({
          key,
          id: ++idx,
          children: value
        }))
      ]
    })
  )
);

/* Code Explanation
// function to transform the given array
const transformData = arr => (
  arr.map(      
    ({name, id, ...rest}) => ({     
      name, id,               
      children: [             
        ...Object.entries(rest)  
        .map(([key, value], idx) => ({     
          key,              
          id: ++idx,          
          children: value         
        }))
      ]
    })
  )
);

*/

const sampleDataArr = [{
    name: 'Tom Holland',
    id: 1,
    Movies: [{
      typename: 'MoviesData',
      id: 12,
      name: 'Spider-Man NWH',
      stars: 4
    }, {
      typename: 'MoviesData',
      id: 13,
      name: 'Spider-Man Far from Home',
      stars: 4
    }],
    Awards: [{
      typename: 'AwardsData',
      id: 6,
      name: 'BAFTA Award',
      year: 2017
    }, {
      typename: 'AwardsData',
      id: 7,
      name: 'Empire Award',
      year: 2013
    }], 
  }, 
];

console.log(
  'transformed data array:\n',
  transformData(sampleDataArr)
);
.as-console-wrapper { max-height: 100% !important; top: 0 }

Explanation

Added inline comments to clarify the code snippet provided.

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

Unable to update state in my React app when clicking on a button

There is a requirement for a button click to filter the job-card array by one specific category. For example, clicking on the button "Marketing" should only show jobs from the array that have the property "jobstags: Marketing". I followed a similar procedu ...

To retrieve data from an AJAX response, you will receive an array in the form of a string

After requesting a list of posts submitted by users from my server, the response I received was a string containing an array of stdClass objects. If it had been an actual array, that would not have been an issue. However, it arrives as a string in the foll ...

Build failure encountered with create-react-app due to protracted duration followed by an error notification

When I created a react project version 15 and ran npm run build, it took an unusually long time (20 mins) and appeared to be frozen. Eventually, I encountered the following error. How can I resolve this issue? enter code heresers/rice/my-app-2/node_modu ...

Access the URL or link in an email using Chrome, as opposed to the default browser, IE8

I have an application that sends out an email with a URL link. When the link is clicked, it opens a new tab in the browser. Currently, the application works fine on Chrome but is not compatible with IE8. However, the client's machine has IE8 as the ...

Looking to activate a button upon clicking a button on a different page using php and javascript

Is it possible for the first user logged in on one page to have a button, and when clicked, enable a disabled button on another page where the second user is logged in? This functionality needs to be implemented using PHP/JavaScript. Thank you in advance ...

What could be causing the d3.js pie chart transition to malfunction?

Today I am experimenting with d3.js to create a unique pie chart from scratch. While following tutorials here as my base, there were modifications made in the code to add personal touches and customization. The challenge arose during Step 6 when introduc ...

Utilizing multiple criteria to filter through a nested array

I am faced with an array structured as follows const treeObj = [ { id: 1, name: 'Section One', items: [ { id: 1, name: 'Section One Item One' }, { id: 2, name: 'Section One Item Two' }, ...

Extract Specific Values via Query for List or Text Array

I'm dealing with a dataset that contains subsets of data; 1 clueweb09-en0003-55-31884 0 1 clueweb09-en0006-21-20387 0 1 clueweb09-enwp01-75-20596 1 1 clueweb09-enwp00-64-03709 1 1 clueweb09-en0005-76-03988 0 2 clueweb09-en0011-28-14585 0 2 clueweb09- ...

Issue with Chrome related to svg getScreenCTM function

Check out the jsFiddle demo I am attempting to utilize the getScreenCTM function to retrieve the mouse position based on SVG image coordinates. It seems to work in IE and Firefox, but not in Chrome. When I define the attributes width and height in the SV ...

AngularJS Jasmine test failure: Module instantiation failed

Everything was running smoothly with my angular app and tests using karma and jasmine. However, after adding a dependency in ui.bootstrap, my app continues to function as expected but now my tests won't run. Here is what I have: app.js - added depend ...

Monitoring websites on a consistent basis and executing actions periodically

My idea is to post a question on a forum (like Stack Overflow) and have a program focus on it. The program would then send me an email when someone responds or answers my post. One approach I thought of is using PHP with file_get_contents or curl. Continu ...

Checkbox not appearing in datagrid when using Material-UI

There are some key code snippets related to the datagrid below const apiRef = React.useRef(null); const [gotApiRef, setGotApiRef] = useState(false); const [gotApiRef2, setGotApiRef2] = useState(false); console.log("apiRef.current: ", apiR ...

The Angular $rootScope.user.userMessage throws an error stating that it is not an object

I am encountering an issue: Error: The object '$rootScope.user.userMessage' is not defined. (evaluating 'typeof $rootScope.user.userMessage') This error arises from the following code snippet: if (typeof($rootScope.user.userMessage ...

Tips for properly sending an array in a PHP ajax response

Executing ajax calls after PHP to retrieve an array of JSON data. The necessary information is prepared, but unsure about the correct method of returning them. $files = array(); foreach($db2_databaselist as $db) { $file = new stdClass(); $file-&g ...

When entering a sub-URL into the browser address bar, the routes do not display as expected

I am encountering an issue with navigating to different routes within my React application. While the home route is visible and functions properly when I start the app locally (npm run dev), I am unable to access other routes. No errors are displayed in t ...

What is the process of utilizing marked plugins within a Vue3 project?

I attempted to integrate the marked plugin into my Vue.js applications. After installing [email protected], I did not encounter any issues during compilation. However, when I viewed the contents in the browser, nothing appeared. My Vue project was built u ...

Pass back the jQuery deferred object from the error section of an Ajax request

I am facing a challenge with loading a file using jQuery Ajax. When the initial location fails, it should attempt to retrieve it from another path. Although the request redirects to the alternate URL, I am not receiving the necessary jQuery deferred from l ...

substitute elements within an array using elements from a different array

Looking to swap object(s) in an array with another array while maintaining the original order. Here is arrayOne: [ { "color": "#f8edd1", "selected": true }, { "color": "#d88a ...

Exploring the structured hierarchy of subdocuments within nested arrays in MongoDB

I'm currently working on a query that needs to meet two criteria: matching a specific userID and also matching a range of IDs. Here's an example of what a document might look like: https://i.sstatic.net/sIF3K.png My approach involved using the ...

Converting Java Decryption from AES/CBC/PKCS5PADDING to NodeJs

I'm having trouble decrypting in NodeJs. It works fine in Java, but I can't seem to get the same result in Node. My NodeJs code is as follows: var crypto = require('crypto'); function decryption (message, key) { var messageArray = ...