开发者社区> 问答> 正文

js如何将两个对象合并成一个对象?

把两个数组合并成一个数组我会。
但是如何使用js将两个对象合并成一个对象呢?
求指点,不胜感激!

展开
收起
a123456678 2016-03-12 09:49:56 9035 0
2 条回答
写回答
取消 提交回答
    1. object.assign(a, b)
    2. let a = {
      ...a,

    ...b
    }

    2019-07-17 19:00:11
    赞同 展开评论 打赏
  • es2015 Object.assign()
    
    var o1 = { a: 1 };
    var o2 = { b: 2 };
    var o3 = { c: 3 };
    
    var obj = Object.assign(o1, o2, o3);
    console.log(obj); // { a: 1, b: 2, c: 3 }
    console.log(o1);  // { a: 1, b: 2, c: 3 }, 注意目标对象自身也会改变。
    Polyfill
    if (!Object.assign) {
      Object.defineProperty(Object, "assign", {
        enumerable: false,
        configurable: true,
        writable: true,
        value: function(target, firstSource) {
          "use strict";
          if (target === undefined || target === null)
            throw new TypeError("Cannot convert first argument to object");
          var to = Object(target);
          for (var i = 1; i < arguments.length; i++) {
            var nextSource = arguments[i];
            if (nextSource === undefined || nextSource === null) continue;
            var keysArray = Object.keys(Object(nextSource));
            for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
              var nextKey = keysArray[nextIndex];
              var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
              if (desc !== undefined && desc.enumerable) to[nextKey] = nextSource[nextKey];
            }
          }
          return to;
        }
      });
    }
    2019-07-17 19:00:11
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
JavaScript异步编程 立即下载
Delivering Javascript to World 立即下载
编程语言如何演化-以JS的private为例 立即下载