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

Having trouble connecting with Node.js and Express; encountering ERR_CONNECTION_REFUSED

I tried following this basic tutorial: After generating the files as instructed, I ran through all the steps but encountered an issue. Regardless of the browser I used, I kept getting "Unable to connect" in Firefox and "This webpage is not available ... E ...

The reactivity of Vuex and Vue does not work as expected when a dictionary is used as a

What is the best approach to make a dictionary reactive as one of my store variables? Unlike an array, dictionaries are not reactive by default. Here's a minimal example I've created: Check out this example on CodeSandbox ...

What is the method for including a placeholder with sequential numbering?

When I click on the "Add String" button, it clones the first table row with an input in the table and adds it to the table. I also need to add a +1 number in the placeholder of the copied element. How can I determine the last placeholder before copying and ...

Updating variable value in a Javascript function

I'm currently working on a signup page and I need to verify if an email address already exists in the database. var emailnum = getEmailCount(`select * from contactinfo where email='${email}'`); console.log(emailnum); // Output shows ...

Exposing external variables within the setInterval function

Here is the snippet of code I am working with: update: function(e,d) { var element = $(this); var data = element.data(); var actor = element.find('.actor'); var value = basicdesign.defaultUpdate( e, d, element, true ); var on = templateEn ...

Manipulate properties of objects with React by assigning values from an array

I am working with various objects and values in my code: const [validFilters, setValidFilters] = useState({}); const [endedEvents, setEndedEventsSort] = useState(false); const [joinedEvents, setJoinedEventsSort] = useState(true); const [startDate, setStart ...

Unveiling the Magic: Transforming Objects into HTML Attributes using AngularJS

I have been working on developing a highly dynamic ng directive that creates tables based on a given data array and configuration object. I am looking for a way to assign attributes dynamically based on an object within the scope. For example, if I have an ...

Vue not triggering computed property sets

As per the guidelines, I should be able to utilize computed properties as v-model in Vue by defining get/set methods. However, in my scenario, it isn't functioning as expected: export default{ template: ` <form class="add-upload&quo ...

When attempting to use JQuery autocomplete, the loading process continues indefinitely without successfully triggering the intended function

Currently, I am utilizing JQuery autocomplete to invoke a PHP function via AJAX. Below is the code snippet I am working with: $("#client").autocomplete("get_course_list.php", { width: 260, matchContains: true, selectFirst: false }); Upon execution, ...

Challenges encountered when attempting to send an array in res.json with the MERN stack

I am facing a challenge while trying to make two separate model calls using the MERN stack. The issue arises when I try to send an array in res.json; extracting the data seems to be problematic. On examining the console log: {data: "[]", status: ...

Can a form be submitted using an Ajax request triggered by a div element instead of an input type submit?

I used to submit the form by triggering $(".btn-update.").click() before, but now that I'm using $(".btn-update").ajaxForm(), the form is not getting submitted. Here is the HTML code: <form id="company-profile-edit-form" name="company-profile-edi ...

Implementing a file download feature in Python when clicking on a hyperlink

I'm attempting to click on the href link below. href="javascript:;" <div class="xlsdownload"> <a id="downloadOCTable" download="data-download.csv" href="javascript:;" onclick=&q ...

I am interested in displaying the PDF ajax response within a unique modal window

With the use of ajax, I am able to retrieve PDF base64 data as a response. In this particular scenario, instead of displaying the PDF in a new window, is it possible to display it within a modal popup? Any suggestions on how this can be achieved? $.ajax ...

What is the best way to keep a button visible at all times and active without needing to be clicked?

<v-card :style="{ textAlign: 'left' }" class="basic-card pa-6" :class="{ 'small-padding': !$vuetify.breakpoint.xl }" elevation="0" flat :height="windowHeight - 104 + 'px&ap ...

Fancybox's Exciting Tandem Events

I am currently experiencing an issue with my popup ajax contact form as it only has one close event... The AJAX contact form I have consists of two buttons, SEND and CANCEL. When I click the SEND button, the Sweet Alert confirmation message displays ...

Tips for efficiently importing a file or folder that is valuable but not currently in use

I'm struggling to find any information about this particular case online. Perhaps someone here might have some insight. I keep getting a warning message saying 'FournisseursDb' is defined but never used no-unused-vars when I try to import t ...

Iterate through each entry in the database and identify and fix any duplicate records

In my form, I have a JSON array that includes the name and value of each input. I am attempting to add an "optionprix" attribute for each input with the "optionname" class based on the corresponding value of the input with the "optionprix" class. Here is ...

You can update a JavaScript string by adding values using the '+=' operator

I have the following function: function generateJSONstringforuncheckedfilters(){ jsonstring = ''; jsonstring = "["; $('body').on('click', 'input', function(){ jsonstring += "[{'OrderGUID&apo ...

Using jQuery to manipulate the image within a specific div element

I'm facing an issue with locating the img src within a div. I've written a function to find all the divs with specific ids: function identifyDiv(){ divArray = $("div[id^='your']"); divArray = _.shuffle(divArray); } This is the ...

Is the exchange between Ajax/jQuery and PHP a two-way street?

My jQuery ajax call looks like this: $.ajax({ type: "POST", url: ajaxurl, data: data, success: function(response){ alert(response); } }); I am retrieving data from PHP using the following code: $data_array = get_data(); forea ...