JavaScript /咖啡求和对象 [英] JavaScript/Coffeescript sum objects

查看:68
本文介绍了JavaScript /咖啡求和对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以这种方式添加/合并(不确定如何调用)某些对象:

I would love to "add/merge" (not sure how to call that) some objects in this manner:

obj1 = { 
  a: 1,
  b: 1,
  c: 1
}

obj2 = { 
  a: 1,
  b: 1
}

obj1 + obj2 => { a: 2, b: 2, c: 1 }

有没有办法实现这一目标?尝试过 Object.assign(obj1,obj2 )但不会像我需要的那样添加属性(它返回 {a:1 ,b:1,c:1 })

Is there any way of achieving this? Tried, Object.assign(obj1, obj2) but It will not add properties like I need it to be done (it returns in { a: 1, b: 1, c: 1})

推荐答案

没有内置的做到这一点的方法,但是您可以枚举一个对象的属性并将其值添加到另一个对象。

There isn't a built-in way to do it but you can enumerate the properties of one object and add their values to another.

const a = { a: 1, b: 1, c: 1 };
const b = { a: 1, b: 1 };
for(const prop in b) {
  a[prop] = (prop in a ? a[prop] : 0) + b[prop];
}
console.log(a);

支票中的 prop是为了避免以 NaN ,方法是将 undefined 添加到 b 中的值。

The prop in a check is so that we don't end up with NaN by adding undefined to the value in b.

您可以使用 reduce 组合 n 个对象,如下所示:

You could use reduce to combine n number of objects like so:

const a = { a: 1, b: 1, c: 1 };
const b = { a: 1, b: 1 };
const c = { a: 1, c: 1 };
const result = [a, b, c].reduce((p, c) => {
  for(const prop in c) {
    p[prop] = (prop in p ? p[prop] : 0) + c[prop];
  }
  return p;
}, {});
console.log(result);

您没有提到要如何处理原型链中的属性。您应该知道,中的会枚举原型链中的属性,而x 中的 prop也将检查原型链。如果只想枚举对象自身的属性,则可以使用 Object.entries()来获取其自身的属性,或者执行 hasOwnProperty(。 。)中检查...在中,并代替x prop >检查。如果您不对模型进行任何原型继承,那么您可能不在乎。

You didn't mention how you wanted to deal with properties in the prototype chain. You should know that for...in will enumerate properties in the prototype chain and prop in x will also examine the prototype chain. If your only want to enumerate the objects own properties then you could use Object.entries() to get its own properties or do a hasOwnProperty(...) check within the for...in and in place of the prop in x check. If you don't do any prototypal inheritance with your models then you may not care.

这篇关于JavaScript /咖啡求和对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆