如何在 ES6+ 中将两个 javascript 对象合并在一起? [英] How do I merge two javascript objects together in ES6+?
问题描述
我生病了&厌倦了总是不得不编写这样的代码:
I'm sick & 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?
推荐答案
您将能够在 ES6 中使用 Object.assign 进行浅层合并/扩展/分配:
You will be able to do a shallow merge/extend/assign in ES6 by using Object.assign:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
语法:
Object.assign(target, sources);
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屋!