Lodash 中的 merge() 函数

给定两个对象 destinationsource,Lodash merge() 函数 将第二个对象 自己的属性 和继承的属性复制到第一个对象中。

const destination = { name: Will Riker, rank: Commander };
const source = { ship: USS Enterprise };

_.merge(destination, source);
destination.name; // Will Riker
destination.rank; // Commander
destination.ship; // USS Enterprise

听起来很像 Object.assign(), 正确的? 尽管 merge() 非常相似 Object.assign()_.assign(),有一些细微的差别。

merge()assign() 之间的差异

第一个细节是 merge() 是 递归 复制对象,所以 _.merge()深拷贝 ,而 _.assign() 是浅拷贝。

const obj = {
  name: {
    first: Will,
    last: Riker
  }
};

const deepClone = _.merge({}, obj);
deepClone.name === obj.name; // false

deepClone.name.first = Thomas;
obj.name.first; // Will

const shallowClone = _.assign({}, obj);
shallowClone.name === obj.name; // true

shallowClone.name.first = Thomas;
obj.name.first; // Thomas

第二个细节是如何 merge() 处理 undefined,如果 source 有一个值严格等于的键 undefinedmerge()不会覆盖该键 destination

let destination = {
  firstName: Will,
  lastName: Riker,
  rank: Commander
};

// Since `source.rank` is undefined, `merge()` wont overwrite
// `destination.rank`.
_.merge(destination, { firstName: Thomas, rank: undefined });
destination.firstName; // Thomas
destination.rank; // Commander

destination = {
  firstName: Will,
  lastName: Riker,
  rank: Commander
};
// But `_.assign()` and `Object.assign()` overwrite `destination.rank`.
_.assign(destination, { firstName: Thomas, rank: undefined });
destination.firstName; // Thomas
destination.rank; // undefined

当您考虑如何 merge() 处理

class Ship {};
Ship.prototype.shipName = USS Enterprise;
const ship = new Ship();

// `merge()` copies inherited properties, so it will copy
// `shipName`
const merged = _.merge({ name: Will Riker, rank: Commander }, ship);
merged.shipName; // USS Enterprise

// `assign()` does **not** copy inherited properties.
const assigned = Object.assign({ name: Will Riker, rank: Commander }, ship);
assigned.shipName; // undefined
© 版权声明
THE END
喜欢就支持一下吧
点赞271 分享
评论 抢沙发

请登录后发表评论

    请登录后查看评论内容