js Convert a flat array into a nested array using map() and reduce() methods

I have a flat array structured as shown below and I am looking to convert it into a nested array with parent-child relationships.


        let arr = [
          {
           id: 4,
           parentId:1,
           value: 20
          },
           {
           id: 1,
           parentId:2,
           value: 20
          },
           {
           id: 2,
           parentId:1,
           value: 20
          },
           {
           id: 3,
           parentId:1,
           value: 20
          },
           {
           id: 4,
           parentId:2,
           value: 20
          },
         ]
    

The desired transformation of this array is illustrated below:


        [{
             id: 1,
             children: [
                { 
                    id: 4,
                    value: 20,
                    parentId: 1
                },
                { 
                    id: 2,
                    value: 20,
                    parentId: 1
                }
                ...
            ]   
        }]
    

Can someone guide me on how to achieve this using the map() and reduce() functions? Any advice would be greatly appreciated!

Answer №1

Utilizing the array#reduce method allows you to group the objects based on their parentId, followed by utilizing array#map to create an array containing both id and children elements.

let data = [ { id: 4, parentId:1, value: 20 }, { id: 1, parentId:2, value: 20 }, { id: 2, parentId:1, value: 20 }, { id: 3, parentId:1, value: 20 }, { id: 4, parentId:2, value: 20 }]

var grouped = data.reduce((r, o) => {
  r[o.parentId] = r[o.parentId] || [];
  r[o.parentId].push(o);
  return r;
}, {});
var result = Object.keys(grouped).map(id => ({id, children: grouped[id]}));

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

JavaScript UDP pinger timeout using the dgram module for nodejs

Currently, I am enrolled in a course where we are tasked with coding a UDP pinger using Javascript with Node.js and Dgram. The assignment provided to us is as follows: Our objective is to create the client-side code for an application. This client should ...

Fixing the Else part of the If Else statement for my JavaScript Toggle button issue in ASP.net-JavaScript application

I am fairly new to JavaScript and looking for some help. I have a button that I want to toggle its background color using if/else logic in JavaScript. My development environment includes ASP.net, C#, JavaScript, and VS2013 Express. The first part of my co ...

A one-page application that packs the punch of a two-page layout

Currently, I am working on developing a small search application using AngularJS and Elasticsearch. The home page (page 1) consists of a basic header, search box, and footer. On the search results page (page 2), users can view the search results along with ...

Using AJAX in jQuery to toggle the visibility of rows in a table with the each

Currently, I am working on an MVC 5 application where I am attempting to utilize a script to toggle the visibility of buttons in each row based on data retrieved from a database using Ajax. function setButtons() { $('#MyList > tbody > ...

Issue with Ant Design form validation

After reading through the documentation, I attempted to implement the code provided: Here is a basic example: import { Button, Form, Input } from "antd"; export default function App() { const [form] = Form.useForm(); return ( <Form f ...

Bringing in additional elements, ensure that there is only a single main root element

Apologies for the beginner question. I am facing an issue while trying to display a .vue file with parent and children components, resulting in a "more than one root element" error. It seems strange to me because the imported components are supposed to be ...

Error encountered while using Jquery's .each() method on a DOM element and attempting to

Trying to utilize the each() function on my DOM to dynamically retrieve a field, I encountered an issue with the following code: var new_entry = new Object(); $('div[name="declaration-line-entry"]').each(function () { new_entry.name = $(this ...

Find the current location of the scroll bar on the view port

Currently, I am utilizing the Addazle React grid for my project. However, I need to incorporate endless scrolling functionality which is not already included in this grid system. Thus, I am tasked with devising my own solution for this issue. To successful ...

Is there a way for me to identify when I am "traveling" along the same path?

I want to create a toggle effect where a view is hidden if the user tries to revisit it. This can be useful for showing/hiding modal boxes. Here's the code I attempted: /* Root Instance */ const app = new Vue({ router, watch: { '$route&a ...

A guide on incorporating JavaScript variables within a GraphQL-tag mutation

I'm having trouble consistently using javascript variables inside graphql-tag queries and mutations when setting up an apollo server. Here's a specific issue I've encountered: gql` mutation SetDeviceFirebaseToken { SetDeviceFirebaseTok ...

Assistance with selecting elements using jQuery

I'm facing a challenge with a code that I cannot change. My goal is to introduce a selector that can choose (upon clicking) all elements below it until the next occurrence of the main element. The catch is that they are not nested, just stacked on top ...

How can I incorporate a new object into an existing object in ReactJS?

I am facing an issue where I have an object named waA that is required in the final step. However, in ReactJS, the new object is not updating the previous object using a switch statement in a function. Below is the code for the object: waA = { jso ...

Struggling to formulate a JSON structure for Treebeard in ReactJS

Seeking guidance on creating JSON structure in React using data traversal methods like the map function. I have experience building JSON in C# with LINQ and lists, but transitioning to ReactJS has left me uncertain about the approach. const prodData = { ...

Using JavaScript to locate a child element within its parent

What is the most effective approach to locate a child element (using class or ID) of a specific parent element using only pure JavaScript without relying on jQuery or other frameworks? In this scenario, I am interested in finding child1 or child2 within p ...

Maintaining accurate type-hinting with Typescript's external modules

Before I ask my question, I want to mention that I am utilizing Intellij IDEA. In reference to this inquiry: How do you prevent naming conflicts when external typescript modules do not have a module name? Imagine I have two Rectangle classes in different ...

Steps to create a new window using Raphael JS

Is there a way to create a new window in Raphael similar to using "_blank"? ...

Tips for retrieving a value from my controller within my directive

Currently, I am working with AngularJS and have created a controller along with a directive. directive = -> scope: items: "=mkTagsInput" link: (scope, element, attributes, controller) -> $(element[0]).tagsinput() $(el ...

VBScript String Array - Error 800A000D: Incompatible Data Types

Having an issue with processing a Variant array of strings in AutoCAD. The array appears valid, but encountering a Type Mismatch error when trying to reference elements or include the array name in a For Each statement. Below is the code snippet: Dim acA ...

Bootstrap gallery with images that resize proportionally

Attempting to create something simple, but currently unsure how to proceed. A few months ago, I had a concept in mind, but unfortunately lost the files and now feeling stuck. Using Bootstrap to construct a gallery with two different image sizes: 1920x1200 ...

What are the steps to start a ExpressJS server for webpages that are not index.html?

I am exploring how to browse/run/view web pages other than just the index.html file in my public folder, which contains multiple HTML files. I am using ExpressJS and NodeJS for this purpose, but every time I start my server, I can only access the index.htm ...