spread运算符_使用Spread运算符合并对象属性

spread运算符

Last week I wrote 6 Great Uses of the Spread Operator, a post detailing how awesome the spread operator (...) is for working with arrays and other iterable objects.  As always my readers chimed in with a few other great uses and which you should check out in the comments.  And of course as soon as I publish the post I find another great use of the spread operator while I tinker with Babel and React:  merging multiple objects' properties into one object!

上周,我写了《 Spread运算符的6大用法》 ,详细介绍了Spread运算符( ... )对于处理数组和其他可迭代对象的效果。 像往常一样,我的读者还有其他一些很棒的用途,您应该在评论中查看。 当然,当我发布该帖子时,我在修补BabelReact时发现了散布运算符的另一种出色用法:将多个对象的属性合并到一个对象中!

JavaScript (The JavaScript)

Wrap any objects you'd like merged into one with braces ({}):

用大括号( {} )将要合并的所有对象包装起来:


const person = { name: 'David Walsh', gender: 'Male' };
const tools = { computer: 'Mac', editor: 'Atom' };

const summary = {...person, ...tools};
/*
Object {
  "computer": "Mac",
  "editor": "Atom",
  "gender": "Male",
  "name": "David Walsh",
}
*/


A new object is created containing all properties and values from the objects provided with the rest operator.  Also note that you can provide any number of objects to merge:

将创建一个新对象,其中包含rest运算符提供的对象中的所有属性和值。 还请注意,您可以提供任意数量的对象进行合并:


const person = { name: 'David Walsh', gender: 'Male' };
const tools = { computer: 'Mac', editor: 'Atom' };
const attributes = { handsomeness: 'Extreme', hair: 'Brown', eyes: 'Blue' };

const summary = {...person, ...tools, ...attributes};
/*
Object {
  "computer": "Mac",
  "editor": "Atom",
  "eyes": "Blue",
  "gender": "Male",
  "hair": "Brown",
  "handsomeness": "Extreme",
  "name": "David Walsh",
}
*/


In the case of a key collision, the right-most (last) object's value wins out:

如果发生键冲突,则最右边(最后一个)对象的值将获胜:


const person1 = { name: 'David Walsh', age: 33 };
const person2 = { name: 'David Walsh Jr.', role: 'kid' };

const merged = {...person1, ...person2}
/*
Object {
  "name": "David Walsh Jr.",
  "age": 33,
  "role": "kid",
}
*/


I love how easy merging objects is using the spread operator.  You can use Object.assign to accomplish the same feat but the spread operator makes things a bit shorter if you don't mind a slightly less descriptive syntax!

我喜欢使用散布运算符轻松合并对象。 您可以使用Object.assign来完成相同的功能,但是如果您不介意描述性语法稍差一点,那么蔓延运算符会使事情变得更短!

Note:  This syntax is not yet support by all browsers but you can use Babel with the transform-object-rest-spread plugin to enable object merging with the spread operator.

注意:并非所有浏览器都支持此语法,但是您可以将Babel与transform-object-rest-spread插件一起使用,以启用对象与spread运算符的合并。

翻译自: https://davidwalsh.name/merge-objects

spread运算符

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值