Is there a way to combine properties from two different objects?

I am working with several JavaScript objects:

{
  x: 5,
  y: 10,
  z: 3
}

and

{
  x: 7,
  y: 2,
  z: 9
}

My task is to add these two objects together based on their keys.

The resulting object should look like this:

{
  x: 12,
  y: 12,
  z: 12
}

Do you have any suggestions or solutions in JavaScript? I have tried using Object.keys.map but it becomes unwieldy when dealing with a large number of elements in my object (around 100).

Answer №1

If you're looking to combine multiple objects using JavaScript, the function below will help you achieve that effortlessly:

var object1 = {
  x: 10,
  y: 20,
  z: 30
};

var object2 = {
  x: 5,
  y: 15,
  z: 25
};

var object3 = {
  x: 8,
  y: 12,
  z: 18
};


function combineObjects(...objects) {
  return objects.reduce((acc, curr) => {
    for (let key in curr) {
      if (curr.hasOwnProperty(key))
        acc[key] = (acc[key] || 0) + curr[key];
    }
    return acc;
  }, {});
}

console.log(combineObjects(object1, object2, object3));

Answer №2

Exploring a bit further, anything goes as long as the items match!

const arr = [{
    a: 12,
    b: { a: 12, c: { a: 12 } },
    c: 17
  },
  {
    a: 12,
    b: { a: 12, c: { a: 12 } },
    c: 17
  },
  {
    a: 12,
    b: { a: 12, c: { a: 12 } },
    c: 17
  }
];

const deepMergeSum = (obj1, obj2) => {
  return Object.keys(obj1).reduce((acc, key) => {
    if (typeof obj2[key] === 'object') {
      acc[key] = deepMergeSum(obj1[key], obj2[key]);
    } else if (obj2.hasOwnProperty(key) && !isNaN(parseFloat(obj2[key]))) {
      acc[key] = obj1[key] + obj2[key]
    }
    return acc;
  }, {});
};

const result = arr.reduce((acc, obj) => acc = deepMergeSum(acc, obj));
console.log('result: ', result);

Answer №3

Give this a shot.

let object1 = 
{ 
  apples:12,
  bananas:8,
  oranges:17
};

let object2 = 
{ 
  apples:2,
  bananas:4,
  oranges:1
};

function sumObjects(obj1, obj2) {
  let total = {};

  Object.keys(obj1).forEach(key => {
    if (obj2.hasOwnProperty(key)) {
      total[key] = obj1[key] + obj2[key]
    }  
  })
  return total;
}

sumObjects(object1, object2);

https://jsfiddle.net/bcpl7vz0/

Answer №4

If each object shares the same keys, you can preselect the keys from one object and then iterate through to create a new result object by combining values at each key.

var o1 = { a: 12, b: 8, c: 17 },
    o2 = { a: 2, b: 4, c: 1 },
    keys = Object.keys(o1),
    result = [o1, o2].reduce(function (r, o) {
        keys.forEach(function (k) {
            r[k] += o[k];
        });
        return r;
    }, keys.reduce(function (r, k) {
        r[k] = 0;
        return r;
    }, Object.create(null)));
    
console.log(result);

Answer №5

If you only have a pair of items:

const item1 = { name: "apple", price: 2.50 }
const item2 = { name: "banana", price: 1.00 }

const total = Object.fromEntries(Object.keys(item1).map(key=>[key,item1[key]+item2[key]])) 

console.log(total)

Alternatively, if you possess multiple items:

const itemsArray = [{ name: "orange", quantity: 3 }, { name: "grapes", quantity: 5 }, { name: "kiwi", quantity: 2 }]

const sum = Object.fromEntries(Object.keys(itemsArray[0]).map(k=>[k,itemsArray.reduce((acc,obj)=>acc+obj[k],0)]))

console.log(sum)

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

Struggling with expanding a Javascript object? Let us assist you!

Imagine having a JavaScript object... app.widget = {} (function (W) { W.superFunction = function() { console.log("Hey!"); } ...other functions... })(app.widget) Now, let's create a clone of this object... app.specialWidget ...

Using AJAX, SQL and PHP to send data to a separate page for processing

This is the code I use to retrieve questions via ajax from a list of questions stored in a SQL database. <form id="reg-form3"> <ul class="nav nav-list primary push-bottom"> <? $db['db_host']="localhost"; ...

Other elements are unable to conceal Material UI InputBase

Displayed below is a navigation bar that sticks to the top, followed by rows of InputBase components from material-ui. Despite setting the background color of the nav bar to white, the input always appears above the nav. This strange behavior stopped when ...

Unable to set background-image on Node (Limited to displaying only images sourced from Flickr)

I am experiencing difficulty with the background-image node property not functioning properly. In order to test this issue, I am using the "Images & breadthfirst layout" demo as an example (accessible at https://gist.github.com/maxkfranz/aedff159b0df0 ...

The function Map() in React-Leaflet cannot be executed, despite the presence of data

I am attempting to replicate the React-Leaflet example of a list of markers. I have an array of objects that I am passing to MarkerList to be transformed into Fragments and displayed on the map. However, my mapping function is not functioning as expected ...

Sending request results to the client's browser in Node.js - A step-by-step guide

I am struggling with figuring out how to send the results of a 'request' to the client browser. This function is executed on my Node.js server. var request = require("request"); function RedirectReceiver(url, currentState, callback){ ; Send ...

What is the best way to transform React API data into props that can be utilized in different components?

I've been struggling with this issue for quite some time now, unable to understand how to manipulate the data in a way that allows me to use it in other components. Although I can display the data correctly, I'm advised to structure it within a f ...

Unable to retrieve obj after using $location.url

I am working with two different views. In the first view, I call a function from the admin controller using AngularJS: <a ng-click="updateAdmin(admin)">update</a> The code in the admin controller looks like this: $scope.updateAdmin = functio ...

I'm having an issue where whenever I click on a different page, I keep getting redirected back to the first page

Upon conducting research, I discovered that by implementing the refined code below, I was able to resolve my issue (my other html was also corrected using this solution) setTimeout(function() { datatable_FTP.ajax.reload(null, false); }, 30000); Although I ...

jquery module for retrieving and updating messages

I want to develop a custom plugin that can be utilized in a manner similar to the following example. This isn't exactly how I plan to use it, but it serves as the initial test for me to fully grasp its functionality. HTML: <div id="myDiv">< ...

Get the JS file by tapping the download button, and access the

In creating the web page, I utilize a modular approach. Leveraging node js and the node-static server are essential components of this process. One specific requirement I have is implementing file downloads from a computer to a device using a button trigg ...

Retrieving a specific Project ID from Asana Task API using Node.js and parsing the JSON response

Utilizing the Asana Task API, we have the capability to retrieve a task's associated projects along with their GID and Notes (description text). The main objective Our aim is to extract the GID of the project containing #websiteprojecttemplate in its ...

Having trouble accessing properties of an undefined object when trying to read 'credentials' in Firebase Auth within ReactJS

I need to verify the user's password again before allowing them to change it. Currently, my Firebase Auth setup is defined in Firebase.js and exported correctly //appConfig = ...(all the configurations here) const app = firebase.initializeApp(appConf ...

Performance problem with 'Point-along-path' d3 visualization

I recently explored a d3 visualization where a point moves along a path, following the code example provided at https://bl.ocks.org/mbostock/1705868. During this movement, I observed that the CPU usage ranges from 7 to 11%. In my current project, there ar ...

Dealing with unique constraint violation in Mongodb when using insertMany

Currently, I'm in the process of working on a project that involves using node.js and mongodb version 5. In my collection, I have implemented a unique index for the Parcel property. However, during testing, an error is triggered: MongoBulkWriteError: ...

Utilize JavaScript to target the specific CSS class

Hello, I am currently using inline JS in my Wordpress navigation menu, redirecting users to a login page when clicked. However, I have been advised to use a regular menu item with a specific class and then target that class with JS instead. Despite searchi ...

How can you ensure that it selects a random number to retrieve items from an array?

I am experiencing an issue with some code I wrote. Instead of displaying a random object from the array as intended, it is showing the random number used to try and display an object. <html> <body> <h1>HTML random objects< ...

Removing an article from a Vue.js localStorage array using its index position

I am facing an issue while trying to remove an item from localStorage. I have created a table to store all the added items, and I would like to delete a specific article either by its index or ideally by its unique id. Your assistance is greatly apprecia ...

Most effective method for showcasing the image once it has been successfully loaded

At the moment, I am considering two methods to display an image after it has been loaded. Initial Method <img id="myImage" /> var img = new Image(), x = document.getElementById("myImage"); img.onload = function() { x.src = img.src; }; img ...

Avoid using the JavaScript 'Sys.WebForms..' function if there is no ScriptManager present on the page

Currently, I am using a single JavaScript binding in the Master Page for my entire project. However, the Master Page does not include a ScriptManager. This means that some pages have Ajax components, such as UpdatePanel, while others do not. The 'Sys. ...