You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何以简写方式实现JavaScript对象对应属性值的累加?

Shorthand Ways to Add Corresponding Object Properties in JavaScript

Awesome question! JavaScript doesn’t have a built-in shorthand operator like += specifically for adding corresponding properties of two objects, but we can put together some clean, concise solutions that feel just as handy. Let’s look at a few options:

1. Reusable Helper Function (Most Clean "Shorthand" for Repeat Use)

If you need to do this operation multiple times, wrapping the logic in a tiny helper function gives you a shorthand-like experience every time you use it:

const addObjectProps = (target, source) => 
  Object.fromEntries(
    Object.keys(target).map(key => [key, target[key] + (source[key] || 0)])
  );

// Usage (super concise!)
let zx = { a: 1, b: 10};
let as = { a: 20, b: 1};
as = addObjectProps(as, zx);
console.log(as); // { a: 21, b: 11 }

This function even handles cases where the source object might be missing a key from the target (it defaults to adding 0 in those scenarios).

2. Inline One-Liner (For One-Time Use)

If you only need to do this once, you can condense the logic into a single line using object spread and Object.entries:

let zx = { a: 1, b: 10};
let as = { a: 20, b: 1};
as = {...as, ...Object.fromEntries(Object.entries(zx).map(([key, val]) => [key, as[key] + val]))};
console.log(as); // { a: 21, b: 11 }

Here, we first spread the original as object, then overwrite each property with the sum of itself and the corresponding value from zx.

3. Using Array.reduce

Another concise approach leverages reduce to iterate over the object keys and build the updated object:

let zx = { a: 1, b: 10};
let as = { a: 20, b: 1};
as = Object.keys(zx).reduce((acc, key) => ({...acc, [key]: acc[key] + zx[key]}), as);
console.log(as); // { a: 21, b: 11 }

This starts with the original as object as the accumulator, then updates each property by adding the matching value from zx.

While there’s no native operator that does exactly what you’re asking for, these methods are the closest you’ll get to a clean shorthand in JavaScript. The helper function is my go-to for readability and reusability!

内容的提问来源于stack exchange,提问作者Kenny Hammerlund

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:05:52