方法一:Object.assign
函数定义
Object.assign(target: object, ...sources: any[]): any;
可以合并多个对象到一个对象中, 返回target
注意:target 对象会被修改
使用示例
'use strict'
var obj1 = {name: "Tom", age: 23};
var obj2 = {name: "Tom", age: 24};
var obj3 = {sex: "Man"};
var obj4 = Object.assign(obj1, obj2, obj3);
console.log(obj1); // { name: 'Tom', age: 24, sex: 'Man' }
console.log(obj2); // { name: 'Tom', age: 24 }
console.log(obj3); // { sex: 'Man' }
console.log(obj4); // { name: 'Tom', age: 24, sex: 'Man' }
方法二 展开语法
var obj1 = {name: "Tom", age: 23};
var obj2 = {name: "Tom", age: 24};
var obj = {sex: "Man", ...obj1, ...obj2}
console.log(obj);
// { sex: 'Man', name: 'Tom', age: 24 }