js 2个对象合并 取属性少的

新手上路,请多包涵

let a = { a: '', b: '' },
b = { a: 1, b: 4, c: 3 };
想要得到 a={a:1,b:4};
有一步到位的方法吗? 像 Object.assign 类似的方法

阅读 3.2k
3 个回答
Object.keys(a).forEach((item,index)=>{
    a[item] = b[item]
})

没看明白,为什么属性a里,一个是空,一个是1,最后得到的是1?

是这个意思吗?比如有多个对象A, B, C,只要其中一个对象里没有这个属性,那么最后得到的这个对象里,就没这个属性?

比如上面的:

let a = { a: '', b: '' },
b = { a: 1, b: 4, c: 3 };

对象a里没有c属性,所以最后得到的数据也没有c属性?

可以参考下用es5实现Object.assign的方法: Object.assign

if (typeof Object.assignless != 'function') {
  // Must be writable: true, enumerable: false, configurable: true
  Object.defineProperty(Object, "assignless", {
    value: function assign(target, varArgs) { // .length of function is 2
      'use strict';
      if (target == null) { // TypeError if undefined or null
        throw new TypeError('Cannot convert undefined or null to object');
      }

      var to = new Object();

      for (var index = 1; index < arguments.length; index++) {
        var nextSource = arguments[index];

        if (nextSource != null) { // Skip over if undefined or null
          for (var nextKey in nextSource) {
            // Avoid bugs when hasOwnProperty is shadowed
            if (Object.prototype.hasOwnProperty.call(target, nextKey) && Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
              to[nextKey] = nextSource[nextKey];
            }
          }
        }
      }
      return to;
    },
    writable: true,
    configurable: true
  });
}

由于只考虑最少的, 所以循环一遍就可以, 调用的时候Object.assignless(a, b);

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题