如何在 ES6+ 中将两个 javascript 对象合并在一起?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13852852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 14:56:44  来源:igfitidea点击:

How do I merge two javascript objects together in ES6+?

javascriptecmascript-6

提问by balupton

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]
  }
}

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+ 肯定会在这方面提供帮助,这将为我们提供类似Object.prototype.extend(obj2...)Object.extend(obj1,obj2...)

So does ES6+ provide such functionality? If not already there, then is such functionality planned? If not planned, then why not?

那么 ES6+ 是否提供了这样的功能呢?如果还没有,那么是否计划了此类功能?如果没有计划,那为什么不呢?

回答by Hyman

You will be able to do a shallow merge/extend/assign in ES6 by using Object.assign:

您将能够使用 Object.assign 在 ES6 中进行浅层合并/扩展/分配:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Syntax:

句法:

Object.assign(target, sources);

Object.assign(目标,来源);

where ...sourcesrepresents the source object(s).

其中...sources表示源对象。

Example:

例子:

var obj1 = {name: 'Daisy', age: 30};
var obj2 = {name: 'Casey'};

Object.assign(obj1, obj2);

console.log(obj1.name === 'Casey' && obj1.age === 30);
// true

回答by Thijs Koerselman

You can use the object spread syntaxfor this:

您可以为此使用对象传播语法

const merged = {...obj1, ...obj2}

For arrays the spread operator was already part of ES6 (ES2015), but for objects it was added to the language spec at ES9 (ES2018). Its proposal as been enabled by default in tools like Babel long before that.

对于数组,展开运算符已经是 ES6 (ES2015) 的一部分,但对于对象,它已添加到 ES9 (ES2018) 的语言规范中。它的提议在此之前很久就在 Babel 等工具中默认启用。

回答by Salakar

I know this is a bit of an old issue but the easiest solution in ES2015/ES6 is actually quite simple, using Object.assign(),

我知道这是一个老问题,但 ES2015/ES6 中最简单的解决方案实际上非常简单,使用 Object.assign(),

Hopefully this helps, this does DEEPmerging as well:

希望这会有所帮助,这也可以进行深度合并:

/**
 * Simple is object check.
 * @param item
 * @returns {boolean}
 */
export function isObject(item) {
  return (item && typeof item === 'object' && !Array.isArray(item) && item !== null);
}

/**
 * Deep merge two objects.
 * @param target
 * @param source
 */
export function mergeDeep(target, source) {
  if (isObject(target) && isObject(source)) {
    for (const key in source) {
      if (isObject(source[key])) {
        if (!target[key]) Object.assign(target, { [key]: {} });
        mergeDeep(target[key], source[key]);
      } else {
        Object.assign(target, { [key]: source[key] });
      }
    }
  }
  return target;
}

Example usage:

用法示例:

mergeDeep(this, { a: { b: { c: 123 } } });
// or
const merged = mergeDeep({a: 1}, { b : { c: { d: { e: 12345}}}});  
console.dir(merged); // { a: 1, b: { c: { d: [Object] } } }

回答by Abdennour TOUMI

ES6

ES6

Object.assign(o1,o2) ; 
Object.assign({},o1,o2) ; //safe inheritance
var copy=Object.assign({},o1); // clone o1
//------Transform array of objects to one object---
var subjects_assess=[{maths:92},{phy:75},{sport:99}];
Object.assign(...subjects_assess); // {maths:92,phy:75,sport:99}

ES7 or Babel

ES7 或 Babel

{...o1,...o2} // inheritance
 var copy= {...o1};

回答by Nathan Wall

The addition of Object.mixinis currently being discussed to take care of the behavior you are asking for. https://mail.mozilla.org/pipermail/es-discuss/2012-December/027037.html

Object.mixin目前正在讨论照顾你所要求的行为。https://mail.mozilla.org/pipermail/es-discuss/2012-December/027037.html

Although it is not in the ES6 draft yet, it seems like there is a lot of support for it, so I think it will show up in the drafts soon.

虽然它还没有出现在 ES6 草案中,但似乎有很多人支持它,所以我认为它很快就会出现在草案中。

回答by RobG

Perhaps the ES5 Object.definePropertiesmethod will do the job?

也许 ES5Object.defineProperties方法可以完成这项工作?

e.g.

例如

var a = {name:'fred'};
var b = {age: {value: 37, writeable: true}};

Object.defineProperties(a, b);

alert(a.age); // 37

MDN documentation: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperties

MDN 文档:https: //developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperties