如何在ES6 +中将两个javascript对象合并在一起? [英] How do I merge two javascript objects together in ES6+?
问题描述
我厌倦了总是不得不编写这样的代码:
I'm sick of tired of always having to write code like this:
function shallowExtend(obj1,obj2){
var key;
for ( key in obj2 ) {
if ( obj2.hasOwnProperty(key) === false ) continue;
obj1[key] = obj2[key]
}
}
或者,如果我不想自己编写代码,请实现一个已经执行过的库. ES6 +肯定会抢救过来,这将为我们提供类似Object.prototype.extend(obj2...)
或Object.extend(obj1,obj2...)
Or if I don't want to write the code myself, implement a library that does it already. Surely ES6+ is coming to the rescue on this will provide us with something like a Object.prototype.extend(obj2...)
or Object.extend(obj1,obj2...)
那么ES6 +是否提供了这样的功能?如果尚不存在,那么是否计划了此类功能?如果没有计划,那为什么不呢?
So does ES6+ provide such functionality? If not already there, then is such functionality planned? If not planned, then why not?
推荐答案
您将能够使用Object.assign在ES6中进行浅层合并/扩展/分配:
You will be able to do a shallow merge/extend/assign in ES6 by using Object.assign:
https://developer.mozilla. org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
语法:
Object.assign( target , sources );
其中 ... sources 表示源对象.
示例:
var obj1 = {name: 'Daisy', age: 30};
var obj2 = {name: 'Casey'};
Object.assign(obj1, obj2);
console.log(obj1.name === 'Casey' && obj1.age === 30);
// true
这篇关于如何在ES6 +中将两个javascript对象合并在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!