How can you extract all values from an ArrayObject using the flatMap method in lodash?

Looking at the Array Object provided, I need to filter the data and group it by a specific key. Here is the Array Object:

    var data = [{
                'value': [{
                    'id': '1',
                    'list': [
                        { 'name': 'test', 'mapp_id': 1 },
                        { 'name': 'test1', 'mapp_id': 1 },
                        { 'name': 'test2', 'mapp_id': 1 },
                        { 'name': 'test3', 'mapp_id': 2 }
                    ]
                }, {
                    'id': '2',
                    'list': [
                        { 'name': 'test4', 'mapp_id': 2 },
                        { 'name': 'test5', 'mapp_id': 2 },
                        { 'name': 'test6', 'mapp_id': 2 },
                        { 'name': 'test7', 'mapp_id': 1 }
                    ]
                }

                ]
            },{
                'value': [{
                    'id': '3',
                    'list': [
                        { 'name': 'test8', 'mapp_id': 3 },
                        { 'name': 'test9', 'mapp_id': 3 },
                        { 'name': 'test10', 'mapp_id': 1 },
                        { 'name': 'test11', 'mapp_id': 1 }
                    ]
                }, {
                    'id': '4',
                    'list': [
                        { 'name': 'test12', 'mapp_id': 1 },
                        { 'name': 'test13', 'mapp_id': 1 },
                        { 'name': 'test14', 'mapp_id': 2 },
                        { 'name': 'test14', 'mapp_id': 2 }
                    ]
                }

                ]
            }]

I have attempted to manipulate the data, but have not achieved full success. Here's the desired data format along with the code I have tried:

    var output = {
                '1': [
                          { 'name': 'test', 'mapp_id': 1 ,'id': '1'},
                          { 'name': 'test1', 'mapp_id': 1 ,'id': '1'},
                          { 'name': 'test2', 'mapp_id': 1 ,'id': '1'},
                          { 'name': 'test7', 'mapp_id': 1 ,'id': '2'},
                          { 'name': 'test10', 'mapp_id': 1, 'id': '3' },
                          { 'name': 'test11', 'mapp_id': 1, 'id': '3' },
                          { 'name': 'test12', 'mapp_id': 1,'id': '4' },
                          { 'name': 'test13', 'mapp_id': 1 ,'id': '4'}
                     ],
                '2': [
                          { 'name': 'test3', 'mapp_id': 2 ,'id': '1'}, 
                          { 'name': 'test4', 'mapp_id': 2,'id': '2' },
                          { 'name': 'test5', 'mapp_id': 2 ,'id': '2'},
                          { 'name': 'test6', 'mapp_id': 2,'id': '2' }, 
                          { 'name': 'test14', 'mapp_id': 2 ,'id': '4'},
                          { 'name': 'test14', 'mapp_id': 2 ,'id': '4'}
                ],
                '3':[ 
                          { 'name': 'test8', 'mapp_id': 3 ,'id': '4'},
                          { 'name': 'test9', 'mapp_id': 3 ,'id': '4'}
                    ]

            };

For further information, the lodash library documentation can be found here.

I have also tried some additional code but haven't achieved the desired outcome. Here's the code snippet:

var result= _.flatMap(data, item => 
        _(item.value)
        .flatMap('list')
        .value()
        );
result=_.groupBy(result, function(b) { return b.mapp_id})

Currently, my code output is as follows:

output = {
            '1': [
                      { 'name': 'test', 'mapp_id': 1 },
                      { 'name': 'test1', 'mapp_id': 1 },
                      { 'name': 'test2', 'mapp_id': 1 },
                      { 'name': 'test7', 'mapp_id': 1 },
                      { 'name': 'test10', 'mapp_id': 1 },
                      { 'name': 'test11', 'mapp_id': 1 },
                      { 'name': 'test12', 'mapp_id': 1 },
                      { 'name': 'test13', 'mapp_id': 1 }
                 ],
            '2': [
                      { 'name': 'test3', 'mapp_id': 2 }, 
                      { 'name': 'test4', 'mapp_id': 2 },
                      { 'name': 'test5', 'mapp_id': 2 },
                      { 'name': 'test6', 'mapp_id': 2 }, 
                      { 'name': 'test14', 'mapp_id': 2 },
                      { 'name': 'test14', 'mapp_id': 2 }
            ],
            '3':[ 
                      { 'name': 'test8', 'mapp_id': 3 },
                      { 'name': 'test9', 'mapp_id': 3 }
                ]

        };

If anyone can guide me on how to achieve the desired result, I would greatly appreciate it.

Answer №1

One approach is to utilize the flatMap function to handle nested properties and then organize the flattened data accordingly.

var data = [{ value: [{ id: '1', list: [{ name: 'test', mapp_id: 1 }, { name: 'test1', mapp_id: 1 }, { name: 'test2', mapp_id: 1 }, { name: 'test3', mapp_id: 2 }] }, { id: '2', list: [{ 'name': 'test4', mapp_id: 2 }, { 'name': 'test5', mapp_id: 2 }, { 'name': 'test6', mapp_id: 2 }, { 'name': 'test7', mapp_id: 1 }] }] }, { value: [{ id: '3', list: [{ name: 'test8', mapp_id: 3 }, { name: 'test9', mapp_id: 3 }, { name: 'test10', mapp_id: 1 }, { name: 'test11', mapp_id: 1 }] }, { id: '4', list: [{ name: 'test12', mapp_id: 1 }, { name: 'test13', mapp_id: 1 }, { name: 'test14', mapp_id: 2 }, { name: 'test14', mapp_id: 2 }] }] }],
    result = _(data)
        .flatMap('value')
        .flatMap('list')
        .groupBy('mapp_id')
        .value();

console.log(result);
.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

To associate each element with its respective ID, you can use the flatMap function in the following way:

var result= _.flatMap(data, item => {
       return  _(item.value)
        .flatMap(function(value){
            return value.list.map(obj => ({...obj, id: value.id}));
         }).value()
        }
);

var data = [{
                'value': [{
                    'id': '1',
                    'list': [
                        { 'name': 'test', 'mapp_id': 1 },
                        { 'name': 'test1', 'mapp_id': 1 },
                        { 'name': 'test2', 'mapp_id': 1 },
                        { 'name': 'test3', 'mapp_id': 2 }
                    ]
                }, {
                    'id': '2',
                    'list': [
                        { 'name': 'test4', 'mapp_id': 2 },
                        { 'name': 'test5', 'mapp_id': 2 },
                        { 'name': 'test6', 'mapp_id': 2 },
                        { 'name': 'test7', 'mapp_id': 1 }
                    ]
                }

                ]
            },{
                'value': [{
                    'id': '3',
                    'list': [
                        { 'name': 'test8', 'mapp_id': 3 },
                        { 'name': 'test9', 'mapp_id': 3 },
                        { 'name': 'test10', 'mapp_id': 1 },
                        { 'name': 'test11', 'mapp_id': 1 }
                    ]
                }, {
                    'id': '4',
                    'list': [
                        { 'name': 'test12', 'mapp_id': 1 },
                        { 'name': 'test13', 'mapp_id': 1 },
                        { 'name': 'test14', 'mapp_id': 2 },
                        { 'name': 'test14', 'mapp_id': 2 }
                    ]
                }

                ]
            }]
var result= _.flatMap(data, item => {
       return  _(item.value)
        .flatMap(function(value){
            return value.list.map(obj => ({...obj, id: value.id}));
         }).value()
        }
);
result=_.groupBy(result, function(b) { return b.mapp_id})
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

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

Step-by-step guide for launching a Next.js/Node application

Currently, I am developing a full-stack project utilizing a next.js application for the front-end and a node/express server for the API. The front-end and back-end are running on separate ports. Here is how my application is configured: https://i.stack.im ...

Unlocking the Secret: Retrieving Click Event Values from a jQuery Function

Is there a way to retrieve the onclick event value change in jQuery when clicking on a DIV? $("ul li").click(function(){ var newValue = $(this).val(); }); $(function(){ alert(newValue); }); ...

Tips for setting up my bot to pull random messages from a channel and send one when an autoresponse is activated

As per the headline, I attempted to utilize fetchMessages in order to monitor the messages being sent in a specific channel. However, when I experimented with this method, it simply generated never-ending blocks of data in the console. Upon inspection, I ...

What is the reason for the reconnect function not activating when manually reconnecting in Socket.IO?

After disconnecting the client from the node server using socket.disconnect(true);, I manually re-establish the connection on the client side with socket.open(). The issue arises when triggering socket.open(); the socket.on('reconnect', (attempt ...

One possible solution to the error of being unable to set headers after they have already been sent to the client is to ensure that the response is returned

Currently, I am working with expressJS and the following is a snippet of my code in the controller: Within the file readstream, there is a condition check that needs to be met for proper data format. If this condition is not satisfied, I do not want to co ...

Uploading an image using ajax with multer

When using Multer to upload an image file to my Node server, I keep getting 'undefined' when trying to use ajax to send the image. Ajax : image = $("#input-file-img").val() const data = new FormData(); data.appe ...

Tips for ensuring sequential execution of $.post requests without ajax alternative

Can I make synchronous requests with $.post in this code snippet? function loadTest() { var questionIDs = []; var count = 0; console.log("getting test"); $.post("db.php", function(data) { obj = jQuery.parseJSON(data); var questionCount = obj.l ...

Vuejs v-for nested loops

After spending countless hours researching, I am determined to solve this problem. My objective is to create a questionnaire similar to a Google Form, with question groups, questions, and answers. The structure of my data looks like this: question_group: ...

The default value of the select option will not be displayed upon loading and will also not appear when another option is selected

I created a form using vue.js that includes a select option dropdown. However, the default value does not display when the form loads, and when a new option is selected from the dropdown, it also does not show. When I use v-for to loop through all options ...

Guide on sending a request to an API and displaying the retrieved information within the same Express application

I recently developed a basic express app with API and JWT authentication. I am now attempting to enhance the app by incorporating page rendering through my existing /api/.. routes. However, I am facing challenges in this process. app.use('/', en ...

Issues with parsing XML data when using the xml2js library

I am looking to extract and populate values from a large XML dataset into a mySQL table. The XML data structure is as follows: <BMS version="1.0"> <Summaries> <Summary Booking_strId="CWBL00D7CB8J8U" Booking_lngId="466244159" Trans_lngId="4 ...

Is d3 Version pretending to be a superior version?

I have encountered an issue with my project that involved using d3 v5.5.0. After transferring it to a different computer and running npm install, the application now seems to be recognizing d3 as a higher version? A crucial part of my program relies on th ...

Adjusting the height of the Tinymce Editor in React Grid Layout after the initial initialization

I am facing a challenge with my React Component that displays a tinymce editor. The task is to dynamically adjust the height of the editor after it has been initialized. To achieve this, I am utilizing the "React Grid Layout" package for resizing the compo ...

`NodeJS Compared to Static HTML`

I need to create a browser client for my Java Rest API and I'm considering the best approach with the least trade-offs. Should I use static HTML files with backbone to connect to the REST API and populate the data fields? Or should I opt for a NodeJ ...

What is the method for renaming Props in Vue components?

I recently embarked on my VueJS journey and attempted to implement v-model in a component, following an example I found. <template> <div class="date-picker"> Month: <input type="number" ref="monthPicker" :value="value.month" @in ...

Imitate the act of pasting content into a Textarea using JavaScript

When data is copied from the clipboard and pasted into an html textarea, there is some interesting parsing that occurs to maintain the formatting, especially with newlines. For instance, suppose I have the following code on a page that I copy (highlightin ...

Navigating to a specific route using React-Router through the root component

How can I implement a search functionality in my application where the navbar's textbox is used to navigate to the search results page no matter the route, such as / or /listing/foo? The issue I am facing is that the conventional method of programmati ...

How is the process of connecting a database to REST through a join operation?

I've got a database featuring two tables, namely orders and orderProducts, connected through a 1:n relationship. My goal is to merge these two tables and present the data in JSON format to my REST tool. To accomplish this, I'm utilizing the foll ...

Retrieve the value of a variable by using either an HTTP GET or POST request

Here's the HTML code snippet that I'm working with: <head> <h1>Sample Page</h1> </head> <body> <form method="POST" action=""> Enter Keyword <input type="text" name="key"> ...

Removing the Tawk.to integration in React Redux using external JavaScript

Seeking help with integrating the Tawk.To Widget into my React APP. The widget (javascript) loads successfully when the page is first opened, but remains present when navigating to another page. How can I properly unmount this script when moving to a diff ...