简体   繁体   中英

How to add object properties together (number)?

Hey so I'm working on a JS project, and I came across an issue where I am trying to add/merge 2 objects together. So basically, there is a base object:

{age: 0,
 lvl: 123,
 xp: 321}

So we have this, and I have another object coming in with

{age: 12,
 lvl: 21}

The result I want is

{age: 12,
 lvl: 144,
 xp: 321}

But that could be easily achieved with just individual property addition. However, I want to come to a point where I don't know what properties the object has, yet they are still added. Oh and the property type will for sure be a number. Any ideas?

Edit: Ok, I see I mis worded some stuff. What I meant by me not knowing which properties it has, I meant that I know that the object may have one-all properties of the first object, just that I don't know which ones the second one has and does have.

Loop through the keys of the second object and add them to the first:

const first = {
    age: 0,
    lvl: 123,
    xp: 321
};
const second = {
    age: 12,
    lvl: 21
};
for (const key in second) {
    first[key] = (first[key] || 0) + second[key];
}
console.log(first);

Read more about for...in loops here .

Write a function that makes a copy of the first object and adds the keys in:

 function addProperties(firstObj, secondObj) { const newObj = Object.assign({}, firstObj); for (let key of Object.keys(secondObj)) { if (newObj.hasOwnProperty(key)) { newObj[key] += secondObj[key]; } else { newObj[key] = secondObj[key]; } } return newObj; } const first = { age: 0, lvl: 123, xp: 321 }; const second = { age: 12, lvl: 21 }; const result = addProperties(first, second); console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM