当然ES6 +必须有一种将两个javascript对象合并在一起的方法,是什么? [英] Surely ES6+ must have a way to merge two javascript objects together, what is it?

查看:306
本文介绍了当然ES6 +必须有一种将两个javascript对象合并在一起的方法,是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我厌倦了总是要写这样的代码:

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?

推荐答案

您将能够通过使用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 > ...来源);

Object.assign(target, ...sources);

其中 ...源表示源对象

注意:请勿将语法定义中的 ...来源与ES6扩展运算符混淆。

Note: do not confuse ...sources in the syntax definition with an ES6 spread operator.

示例:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆