Create a tree structure using the flatMap function

Can anyone help me transform a flat array into an array of objects with children in JavaScript? The desired output format should look something like this:

//source format

const arrayObjects = [
  { name: "Alice", lastname: "Silva", age: 25, type: "A", city: "São Paulo" },
  { name: "Bruno", lastname: "Pereira", age: 30, type: "A", city: "Belo Horizonte" },
  // more objects here
];

//expected format

const arrayOutPut = [
  {
    age: 65,
    type: "A",
    children: [
      {
        age: 35,
        type: "A",
        // more properties here
      }
    ]
  }
]

If you have any suggestions on the most efficient way to achieve this transformation using JavaScript, please let me know. I've attempted solutions involving flatMap and reduce but haven't been successful so far.

Answer №1

While I'm not certain if this is the optimal approach, here's how I would tackle it

const dataEntries = [
  { name: "Alice", lastname: "Jones", age: 22, type: "X", city: "New York" },
  { name: "Bob", lastname: "Smith", age: 29, type: "Y", cityName: "Los Angeles" },
  { name: "Charlie", lastname: "Brown", age: 35, type: "Z", city: "Chicago" },
];

// identify distinct types
const uniqueTypes = [...new Set(dataEntries.map(({type}) => type))];


const finalResult = uniqueTypes.map(type => {
// retrieve elements belonging to a type
 const elmntsOfType = dataEntries.filter(obj => obj.type === type)
 .sort((a, b) => a.age - b.age)
 
 // sum up ages
 const totalAge = elmntsOfType.reduce((acc, {age}) => acc += age,0)
 
 return {type, totalAge, children: elmntsOfType}
});

console.log(finalResult);

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

Loop through each JSON object and insert it into an HTML element

I am working on looping through a JSON object and converting it into HTML. While I can iterate through all the objects in the JSON, I am having trouble extracting just the first object. var res = '[{"ID":"246","mobile":"samsung","feedback":"feedback ...

What could be causing the React variable to malfunction within my state object?

class ColoredSquares extends React.Component { constructor() { super(); this.selectedColor = 'green'; } state = { backgroundColor: this.selectedColor, width: "50px", height: "50p ...

What method should I use to identify the type of error being handled by ajaxError?

Dealing with AJAX errors in a web application utilizing jQuery is proving to be challenging for me. I have set up an event handler to manage AJAX errors in the following way: $('body').ajaxError(error_handler); Despite receiving information in ...

Looking for the largest numbers in an array using C++

I am looking to find the largest number in an array to the left and right of the current index. For example, if my array is: 1, 3, 2, 4, 3; I want to output: //Left Right 1 4 //no bigger on left, so 1; the biggest on right is 4 3 4 3 4 4 4 4 3 I need a ...

How can I customize the pull-down menu options depending on the selected checkbox setting?

Here are the menu options I have defined: <label><strong>Release #1:</strong></label> <select id="selectedBaseRelease"> <option value="/~releases/file2">ICC2_O-2018.06</option> <option v ...

Utilize Angular to create a dropdown filter activated by a click event

Having trouble filtering or searching for relevant data using a dropdown input? The task is to select an option from the dropdown and click on the button to filter or display the corresponding data in a table using Angular. Directly achieving this works, b ...

What is the process for verifying the password field in bootstrap?

In my asp.net project using bootstrap, I have implemented password field validation. When the user clicks on the password field, an information box is displayed. <div id="pswd_info"> <h4>Password requirements:</h4> <ul> ...

The results generated by the Google Maps API are consistently consistent

const request = require('request'); var geocodeAddress = (location) => { var encodedLocation = encodeURIComponent(location); request({ url: `http://www.mapquestapi.com/geocoding/v1/address?key=APIKey&location=${encodedLocation}` ...

Spinning objects in three.js using tween.js to move around the global axis

Currently, I am working on tween-rotating a 3D cube. Thanks to this helpful post (How to rotate a object on axis world three.js?), I have successfully achieved rotation without any issues. Now, my goal is to transfer the rotation achieved through setFromRo ...

How can I retrieve JSON information from the wunderground API?

I have an async function below that connects to a weather API and I am trying to extract two data points: Temperature in Fahrenheit & Celsius. The API_Key has been removed, but it can be obtained for free on the site if needed. Although my console.log(res ...

What is the most effective way to alter the elements in a JavaScript array based on the total count of another element's value?

I have a task where I need to manipulate an array by adding or removing elements based on the total count of another value. let data = [ { "details": [ { "Name": "DataSet1", "Severity": "4& ...

"System for dispensing machines that uses Visual C++ to track and dispense coins

Recently, I was assigned to work on a new project in C++, and after days of contemplation, I am still struggling with the design phase. The project involves implementing changes to customer tills at Ruddles, a local department store. The requirement speci ...

In Vue Js, the function createUserWithEmailAndPassword does not exist within _firebase_config__WEBPACK_IMPORTED_MODULE_3__.default

My createUserWithEmailAndPassword function seems to be malfunctioning. Here is the code snippet I am using - config.js import firebase from 'firebase/app' import 'firebase/firestore' import 'firebase/auth' const firebaseCon ...

Update component state based on input value

Trying to update the state of an input within a component and utilize it in app.js. How can this be achieved using props? Attempted onChangeText={(tips) => this.setState({comment})} but only receiving undefined results.. const Comments = (props) => ...

Handling a series of lines within a 2-dimensional array or document

As a beginner in programming, I have been self-studying and find the examples in my book to be too easy. To challenge myself and improve my Java skills, I have decided to work on a more difficult problem related to one of my hobbies - lotteries. Specifical ...

Implementing Dynamic Styling Using Parent Component in React Native

I am facing an issue with a <Text> component that is receiving a style through props... TextFile.js: <Text style={styles.text}> This is a line of text and this might be a second line </Text> screenFile.js: <View style={styles.v ...

"Error: Unable to locate the specified HTML ID within the dynamic

With the use of JavaScript, I am dynamically creating td elements and assigning IDs from a for loop. However, I am encountering an issue where my onclick event is unable to fire because it throws an error stating that the ID cannot be found. Despite inspec ...

Fill in a dropdown using the options selected from another dropdown menu

I have developed the following code snippet: User: <select id="sel_depart"> <option value="0">All users</option> <?php $all_users = User::getUsersAdmin(); foreach($all_users as $value){ ?> <option value="<?php ...

Preserve the order of post types using jQuery sortable in the WordPress Admin panel

I am working with a custom post type called 'items' and I want users to be able to set a global order for these items. The goal is to have the ability to rearrange the items in a specific order using jQuery UI's sortable() function. However, ...

Discovering a way to capture the space bar event in a number input field with JavaScript

Is there a way to capture space bar input with an onchange event in JavaScript? <html> <head> <script type = "text/javascript"> function lala(aa){ console.log(aa + " dasda"); } </script> </head> <body> <input ty ...