Organize a collection of objects into a fresh array

I am facing an issue where I have an array and I need to transform it into an array of its children elements.


        var data = [{
            name: 'Cars',
            content: 'BMW',
            value: 2000
          },
          {
            name: 'Cars',
            content: 'Fiat',
            value: 542
          },
          ...
        ]
    

The desired end result should look like this:


        [
            {
                name: "Children Array",
                children: [
                    {
                        name: "Cars",
                        children: [
                            {
                                name: "BMW",
                                value: 2000
                            },
                            ...
                        ]
                    },
                    ...
                ]
            }
        ]
    

This is what I have done so far:


                    // JavaScript code goes here
                
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

I am struggling with implementing the second layer of children. Any suggestions or advice would be greatly appreciated.

Answer №1

To visualize the data effectively, consider grouping it and presenting the final layout.

var data = [{ name: 'Cars', content: 'BMW', value: 2000 }, { name: 'Cars', content: 'Fiat', value: 542 }, { name: 'Cars', content: 'Mercedes', value: 745 }, { name: 'Cars', content: 'Toyota', value: 965 }, { name: 'Cars', content: 'Honda', value: 754 }, { name: 'Cars', content: 'VW', value: 123 }, { name: 'Cars', content: 'Ford', value: 200 }, { name: 'Fruits', content: 'Apple', value: 500 }, { name: 'Fruits', content: 'Orange', value: 769 }, { name: 'Fruits', content: 'Banana', value: 120 }, { name: 'Fruits', content: 'Strawberry', value: 48 }, { name: 'Fruits', content: 'Mango', value: 653 }, { name: 'Colors', content: 'Red', value: 965 }, { name: 'Colors', content: 'Black', value: 931 }, { name: 'Colors', content: 'BMW', value: 423 }, { name: 'Colors', content: 'BMW', value: 964 }, { name: 'Colors', content: 'BMW', value: 436 }],
    result = _(data)
        .groupBy('name')
        .map((group, name) => 
            ({ name, children: _.map(group, ({ content: name, value }) => ({ name, value })) }))
        .value(),
    final = [{ name: "Children Array", children: result }];

console.log(final);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

Answer №2

If you want to achieve the same outcome using ES6 only, you can utilize Object.entries and reduce:

const data = [{ name: 'Cars', content: 'BMW', value: 2000 }, { name: 'Cars', content: 'Fiat', value: 542 }, { name: 'Cars', content: 'Mercedes', value: 745 }, { name: 'Cars', content: 'Toyota', value: 965 }, { name: 'Cars', content: 'Honda', value: 754 }, { name: 'Cars', content: 'VW', value: 123 }, { name: 'Cars', content: 'Ford', value: 200 }, { name: 'Fruits', content: 'Apple', value: 500 }, { name: 'Fruits', content: 'Orange', value: 769 }, { name: 'Fruits', content: 'Banana', value: 120 }, { name: 'Fruits', conten...

const groupData = (d) => {
  let grouped = Object.entries(d.reduce((result, currentValue) => {
    result[currentValue.name] = [...result[currentValue.name] || [], currentValue];
    return result;
  }, {}));

  return grouped.reduce((finalResult, currentGroup) => {
    finalResult.children.push({
      name: currentGroup[0],
      children: currentGroup[1]
    });
    return finalResult;
  }, {name: "Children Array", children: []});
}

console.log(groupData(data));

The concept involves initially grouping the data by their names into an object using reduce, then obtaining the entries of that object and further reducing on them to arrive at the desired output.

Ensure to commence the main reduce function with your predefined object structure for smoother execution.

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 significance of having 8 pending specs in E2E Protractor tests on Firefox?

Each time I execute my tests, the following results are displayed: There were 11 specs tested with 0 failures and there are 8 pending specs. The test execution took 56.861 seconds to complete. [launcher] There are no instances of WebDriver still running ...

Iview Table UI Cell

Is there a way to retrieve the cell data from a library iview table in Vue.js upon clicking? I am looking to capture both the value of the cell and the title of the column, and then modify the CSS of that particular cell. For instance, clicking on one ce ...

Generate an array of objects using the values from a different array of objects

I have an array of objects: const users = [ { name: 'Alice' }, { name: 'Eve' } ] However, I want to transform it into an array like this: const updatedUsers = [ { key: 'Alice', value: 'Alice', text: 'Al ...

Updating is not happening with ng-repeat trackBy in the case of one-time binding

In an attempt to reduce the number of watchers in my AngularJS application, I am using both "track by" in ngRepeat and one-time bindings. For instance: Here is an example of my view: <div ng-repeat="item in items track by trackingId(item)"> {{ : ...

What is the best way to organize a set of user-defined randomly generated numbers in Java?

Greetings Stack Overflow community! I am relatively new to Java and currently learning how to implement sorting algorithms. My goal is to generate a set of random numbers within a range of 1 - 10 and then sort them. However, I'm unsure of the best app ...

Connecting a button's action to a specific element in an array using AJAX and Firebase

I am currently working on a project that involves making an AJAX request from a social API and then appending the results with a button inside the div. This button is meant to save the corresponding item in the array to my Firebase database. For brevity, ...

Displaying Image Preview in Angular 2 After Uploading to Firebase Storage

At the moment, I am facing an issue where the uploaded image is not being displayed after the uploadTask is successful. This problem arises due to the asynchronous loading nature of the process, causing the view to attempt to display the image before the u ...

Using Angular select asynchronously within a custom directive

Despite my efforts, I am struggling to get an angular select with async to work properly. It seems to be mostly working, but not entirely. Consider the controller below: $scope.stuff = {}; $scope.stuff.blah = "SOME_KEY"; External.list().then( function ...

Vue router is unable to verify the user's authentication

I have certain app routes that are supposed to be restricted to admins only. I've added requiresAdmin: true, to the meta of those routes, but for some reason it doesn't prevent other users from accessing them. Code Note: I've included comme ...

What is the reason that prototypes are not passed down through inheritance?

Can anyone shed light on why Validator.js is structured the way it is initialized (as shown in the first code snippet) and the reason behind the inability to call the validate method (as demonstrated in the second snippet)? I am currently experimenting wi ...

The error message from Object.create() indicates that the argument provided is not recognized as

Description Within my project, I am handling a JSON file, parsing it into an object, and attempting to transform it into an instance of the ProjectFile class using Object.create(). Code let tmpFileContent = fs.readFileSync(tmpPath, {encoding: 'utf- ...

display alternative text before an image is loaded on the screen

Is there a way to display text instead of an image before the image loads? I have a website with an image as the title, causing the page to load fully before the title image is loaded later. Is there a solution for this issue? ...

The function getElementbyId is not recognized

My JavaScript code is supposed to change the color of a button, but I'm running into an issue where it says that getting the button is not a function. Strangely enough, the same function (with the same capitalization and case) works perfectly just a f ...

creating curved lines in three.js

I'm looking for assistance in creating a globe using three.js where I can project arcs representing exports and imports between countries. I have a basic globe set up, but I need guidance on the following: 1. How to use country shape files instead of ...

It is not possible to delete a class from an element once it has been added

Issue can be replicated by visiting the following URL: Click on the hamburger icon to open the navigation menu Click on "Services" Click "< Services" within the submenu to attempt to go back For some reason, the removeClass method is not removing t ...

traversing a dynamic JSON array

I'm currently developing a web application that retrieves data from a webpage using the Yahoo Query Language API to generate a JSON array. However, I've encountered an issue where the array structure varies when there is only one "race" on the pa ...

Converting an array of 8-bit unsigned integers into a string without the

Currently, I am working on extracting JSON data from an HTML document stored in a Uint8 array. The process involves converting the array to text and then isolating the JSON within a script tag. To achieve this, I initially converted the array into text fo ...

What is the best way to display the contents of an array that contains another array within it?

I need help looping through this array and displaying the "roleName" value. I want to use the map method to iterate over it. { "userMenuDTO": { "menuId": "13", "menuName":"PruebaMenu900 ...

Can you explain the role of the next() function in middleware/routes following the app.use(express.static(...)) in Express

When dealing with serving static assets generated from React source code using npm run build, the following method can be used: app.use('/', express.static(path.join(__dirname, 'apps', 'home', 'build'))) To protect ...

Using ReactJS and react-router to exclude the navigation menu on the login page

I have a LoginPage designed like this: https://i.sstatic.net/yzovV.png After logging in, you will be directed to this page: https://i.sstatic.net/pZFou.png Now, I want the login page to have no navigation and look like this: https://i.sstatic.net/1sH9v ...