How can I merge an array of objects in lodash?

I am facing a challenge with merging an array of objects in JavaScript. My goal is to combine them into a single object using either a JS library or lodash.

Here is how my array looks:

[{
    2017: {
      a: "100",
      b: "200"
    },
    2018: {
      a: "101",
      b: "202"
    },
    ...
  },

  {
    2017: {
      a: "300",
      b: "400"
    },
    2018: {
      a: "303",
      b: "404"
    },
    ...
  },

  ...
]

What I aim for is the following result:

[{
  2017: {
    a: "400",
    b: "600"
  },
  2018: {
    a: "404",
    b: "606"
  },

  ...
}]

Is there a straightforward method to achieve this?

Answer №1

Here's an example:

let data = [
                {
                    2017: {
                        x: "10",
                        y: "20",
                    },
                    2018: {
                        x: "11",
                        y: "22",
                    },
                },
                {
                    2017: {
                        x: "30",
                        y: "40",
                    },
                    2018: {
                        x: "33",
                        y: "44",
                    },
                },
            ].reduce((acc, obj) => {
                Object.keys(obj).forEach(year => {
                    if (acc[year]) {
                        acc[year]["x"] += parseInt(obj[year]['x'])
                        acc[year]["y"] += parseInt(obj[year]['y'])
                    } else {
                        acc[year] = {
                            x: parseInt(obj[year]['x']),
                            y: parseInt(obj[year]['y'])
                        }
                    }
                })
                return acc;
            }, {});

            console.log(data)

The Object.keys method is only needed if the years vary within the objects in the array. If they are always 2017 and 2018, you can omit it.

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

Transmit data in JSON format from an Android device to a PHP server using the POST method and HttpURLConnection

I'm having trouble establishing a connection between my Android app and WampServer on the local network. Fetching data from the server has been successful, but I face an issue when attempting to send data to the server. I've implemented a Servi ...

resolve problems with Jquery scripts

Having some issues with importing a script from another file in jQuery. I have tried using $.getScript and $.ajax(); how can I incorporate a script like require.js in jQuery? util.js function getSessionInformation () { $.ajax({ url: '../contr ...

Having trouble with AngularJS $location.path() not redirecting properly?

Why am I unable to redirect to a different URL using $location.path in angular.js? .controller('CheckCtrl', function($scope, $localStorage, $location) { $scope.check = function(){ if($localStorage.hasOwnProperty("accessToken") === t ...

Are there any cross-platform inter-process communication APIs available in both C++ and Javascript?

In the process of developing an app, I am faced with the challenge of passing messages between a C++ application and a Javascript web app. While I have experience writing sockets code in both languages when required, I am now looking for a higher-level me ...

Having trouble accessing Google Spreadsheets in CSV format but unable to do so in JSON format?

I have been experimenting with Google's Visualization API to retrieve data from a specific row in a Google Spreadsheet based on a given string in the column labeled "key". When I run the following code, the success function is triggered and I receive ...

"Learn how to use socket.io in conjunction with the express generator to create individual sockets for each unique link

I'm working on a typical express-generator app where I have some code in my controllers folder: router.get('/:id([A-Za-z0-9_]{5,25})', function(req, res, next) { res.render('my-page.html', { title: 'Messag ...

Syntax rules for JSON schema

I am interested in creating a validator for JSON files following the JSON schema paradigm. I have been searching for a grammar that outlines the JSON schema but haven't had any success. Is there a formal specification available for the JSON schema tha ...

dealing with errors coming from a child asynchronous callback function

function main(){ try { subCallbackFunction(1,(err,res) =>{ if(err){ throw Error(err); } }) } catch (e) { /// Handling error from subCallbackFunction inside this catch block ////// conso ...

Combining Repetitive Elements in an Array

Trying to combine an array of products with the same order_id while also including all objects from a second products array. Below are some sample orders: const orders = [ { "order_details": { }, "order_id": "1", ...

Are there any alternative methods for clearing form fields following a successful thunk dispatch in React?

When implementing a Post API call in Thunk, I dispatch a boolean success key for successful requests and an error message for errors. Now the goal is to clear form data upon success and display the error message upon an error. To achieve this, I utilize ...

Guide to clicking on a user and displaying their details in a different component or view using Vue.js router

Currently working on a Vuejs project that requires the following tasks: Utilize an API to fetch and display a list of users (only user names) on the home page. Create a custom search filter to find users based on their names. Implement functionalit ...

What's preventing canvas from working offline but functioning properly on the TRYIT platform?

I have created some canvas-related code that works perfectly on TRYIT editor, but it fails to work locally when I copied the code into a file and tried to run it. This code is designed to take an image, set the width and height of a canvas based on that i ...

Load content from a remote page using AJAX into a JavaScript variable

Looking to retrieve a short string from a server without direct access to the data in XML or JSON format. Utilizing either .load or .ajax for this purpose, with the intention of parsing the data into a JavaScript array. The target page contains only text c ...

Utilizing ng-style with a ForEach loop on an Object

How can I dynamically add a new style property to objects in an array in Angular, and then use that property inside ng-style? CommentService.GetComments(12535372).then(function () { $scope.comments = CommentService.data(); angular.forEac ...

Troubles encountered when cascading val(), text(), and data()

Here is my JavaScript/jQuery code: $select.append($("<option />") .val(this.id) .text(this.text) .data('name', this.name) .data('isstorage', this.isstorage)); Although it successfully assigns values to t ...

The onChange function in React JS for a Material UI 'number' TextField retains the previous value

In this element, I have an onChange function: <TextField id="rowinput" type="number" defaultValue={this.defaultRows} // defaultRows = 1 inputProps={{ min: "1", max:"5"}} onChange= ...

Displaying AJAX Confirmation in a Popup Window

My form is set up to insert data into a database via an AJAX request. Upon successful insertion, the "rentinsert.php" will display a success message on the page that reads "Your order has been placed". However, I would like this success message to appear i ...

Steps for importing a JavaScript file from Landkit into a Vue project

Currently, I am working on an interesting project and utilizing Vue with Landkit Bootstrap. However, I am encountering issues with the JavaScript behavior of the Landkit component. I usually import the following links in my index.html file, but in the new ...

Is there a way to prevent a link from activating when I click on one of its internal elements?

Within a div nested inside an "a" tag (specifically in Link within next.js), there is another div labeled as "like." When clicking anywhere within the main div, the intention is for it to redirect to the destination specified by the "a" tag. However, if th ...

Utilize node.js to run a local .php file within a polling loop

Here is the purpose of my application in brief. I am using a PHP file to read data via an ODBC connection and then write that data to a local database. This PHP file needs to be executed LOCALLY ON THE SERVER every time a loop is processed in my node.js, ...