Combining objects using mathematical operations for identical properties in JavaScript

Imagine I have two sets of data:

const obj1 = {
  CRITICAL: 0,
  ERROR: 1,
  INFO: 0,
  WARNING: 0,
};

const obj2 = {
  CRITICAL: 0,
  ERROR: 0,
  INFO: 0,
  WARNING: 1,
};

I'm looking to merge them into a single object with the summed values for each property:

{
      CRITICAL: 0,
      ERROR: 1,
      INFO: 0,
      WARNING: 1,
    };

The method I've used so far is:

Object.keys(obj1).reduce((prev, curr) => {
  prev[curr] = obj1[curr] + obj2[curr];
  return prev;
}, {});

However, I believe there may be more efficient ways to achieve this. Any suggestions on alternative approaches would be greatly appreciated.

Answer №1

This version is quite similar to your original one, but it appears to be a bit more organized and streamlined.

It also guarantees that the resulting object will contain all keys from both objects, setting the value of the missing key in obj2 to 0 when it does not exist in obj.

const obj = {
  CRITICAL: 0,
  ERROR: 1,
  INFO: 0,
  WARNING: 0,
  OBJECT1: 1
}

const obj2 = {
  CRITICAL: 0,
  ERROR: 0,
  INFO: 0,
  WARNING: 1,
  OBJECT2: 1
}

console.log(
  Object.entries(obj).reduce(
    (prev, [key, value])=> {
      prev[key] = value + (prev[key] || 0)
      return prev
    },
    { ...obj2 } // use spread operator for immutability
  )
)

Explanation: In this code snippet, I have initialized the accumulator (prev) as a shallow copy of obj2. This ensures that all properties present in obj2 are retained in the final object, maintaining their values even if they do not match with any property in obj.

I have also set a default value of zero for obj2[key] in case the key is not found, ensuring that all properties in obj are included in the output object with their original values when there is no corresponding property in obj2.

To enhance safety, you could consider adding type checks for the values to ensure they are numbers. Overall, though, the implementation seems robust enough.

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

There was an issue with the JSON parsing process due to an unexpected token 'o' at position

Trying to extract titles from a JSON object for a specific feature, here's an example of the JSON structure: [ { "title": "Example 1", "url": "http:\/\/www.example1.com\/" }, { "title": "Example 2", "url": "http:& ...

How can I add content using HTML or JavaScript?

How can I append a .txt file using HTML or Java without ActiveX prompts getting in the way? It's becoming quite annoying! Is there a simple way to script this task without having to deal with ActiveX? The current script snippet looks something like ...

Rendering a component and updating state with inline onClick event handlers

When discussing the concept of pure render methods in React and highlighting the serious anti-pattern of setting state inside the render function, how strictly should this be adhered to? It is understood that triggering a setState within the render functio ...

JavaScript Challenge: Calculate the Number of Visible Characters in a Div

I have a div with text content (a string of length S) that is fixed in size but can be of any length. When the text exceeds a certain point (referred to as L), it gets truncated, and the portion beyond that limit becomes invisible. In other words, characte ...

What is the best way to automatically select options in a dynamic dropdown menu

In my code, I have a list of user records. One column has a dropdown to change the produced by. The ng-change function is working fine. However, after refreshing the page, the dropdown does not show the last selected option. Please review my code below - ...

Using jQuery and JavaScript to swap images depending on the option chosen in a dropdown menu

On my existing ecommerce website, I have a dropdown menu with the following code: <select data-optgroup="10201" class="prodoption detailprodoption" onchange="updateoptimage(0,0)" name="optn0" id="optn0x0" size="1"><option value="">Please Selec ...

Position does not exist

I'm currently working on developing an application form that can be submitted by applicants based on the position they are interested in. However, I am facing an issue when trying to click submit on the application form, resulting in the error display ...

JQuery is blocking the submission of an HTML form

During my exploration of an AJAX/JQuery tutorial for a registration script that interacts with PHP/MySQL and is submitted via JQuery, I encountered a recurring issue. The problem lies in the form submitting directly to the action page instead of its intend ...

What could be causing this JavaScript to output undefined?

const urls = [ "http://x.com", "http://y.com", "http://z.com", ]; for (let j=0; j<urls.length; j++) { setTimeout(function() { console.log(urls[j]); }, 3000); } I'm inserting this code snippe ...

Looking for subsequence in dropdown choices with no assigned values

I need assistance with searching for a specific substring within text that is fetched from options generated by MySQL. How can I retrieve the selected option's text value in order to search for my desired substring? $(document).ready(function() { ...

Save pictures in MongoDB using GridFS or BSON format

As a newcomer to MongoDB, I am seeking advice on the best way to store images in the database. Gridfs and BSON seem to be the most common options, but I'm unsure about their respective pros and cons. The main difference I'm aware of is the 16MB s ...

Spinner displayed upon task completion

Currently, I am developing a project using Spring Boot. I would like to display a spinner on my page to indicate that a task involving heavy calculations is in progress. Even though the page may take up to 5 minutes to load, my spinner only appears for t ...

ReactJS: Unable to navigate to a new page when moving from a page with automatic refresh

Every 5 seconds, I automatically refresh a page (Page1) using setTimeout and a callback function. However, every time I navigate to a new page (Page2), it quickly redirects back to Page1 after a few moments. I have tried using window beforeunload event l ...

Discovering the method to incorporate a data-icon attribute within select options using vue.js

UPDATE before modification dataIcon: " @/images/flag-ukraine.svg" after modification dataIcon: require("@/assets/svg/flag-ukraine.svg"), notable change with require() I am using Materialize CSS select. When I use a URL for dataIcon ...

Having trouble with a Reactjs Facebook login library - update the componentClicked function to be async

Currently, I am working on incorporating Facebook login into my React application using Redux. Within my loginUser.js file, the "FacebookLogIn" component appears as follows: <FacebookLogin appId="375026166397978" autoLoad={true} fields="name, ...

Having trouble with babel-loader, encountering an issue with UglifyJS (ES6) causing errors

Recently, I integrated the FlipClockJs vue component into my project and it was functioning properly during development when I executed yarn encore dev However, upon running yarn encore production An error cropped up as follows: ERROR Failed to ...

Tips for adding images using v-for in Vue 3

Having some trouble creating a set of images using a v-for loop, as it seems to be not recognizing the variables inside the tag. The picture is broken and the alt attribute just shows me {{ item.alt }}. Here is my HTML: <section class="our-technolo ...

Retrieve a single element from each array stored in MongoDB

Can someone help me with a query in MongoDB? I have a document structure like this, and I am looking to utilize the $addToSet operator to add a value to one of the items within the 'votes' field. However, I also need to remove that value from all ...

Using Websockets in combination with AngularJS and Asp.net

While working on my application that uses AngularJS with Websocket, I encountered a specific issue. The WebSocket communication with the server works fine as users navigate through different pages in Angular. However, when a user decides to refresh the p ...