【问题标题】:Javascript (ES6 + Lodash) merge source object with another updating only common properties, deeplyJavascript(ES6 + Lodash)将源对象与另一个仅更新公共属性的对象深度合并
【发布时间】:2020-03-03 11:24:08
【问题描述】:

我必须用提供的对象深度更新对象 ,仅保留在源对象中找到的属性/路径。 我尝试了 Lodash.merge,但它合并了第二个对象的所有属性,我只想合并在源对象中找到的属性。

这是一个例子:

const ob1 = {
  a1: {
    b1: 2
  },
  a2: 5
}

const obj2 = {
  a1: {
    b1: 4,
    b2: 9
  },
  a3: 6
}

expected result = {
  a1: {
    b1: 4
  },
  a2: 5
}

我想要使用 es6 或 lodash utils 的最简单的解决方案。

有什么想法吗?谢谢!

【问题讨论】:

  • “我试过 Lodash.merge” 你可以给我们看看这个吗?
  • 如果obj2 没有obj1 中存在的密钥怎么办?应该从obj1 中删除还是设置为未定义?
  • 如果密钥存在于 obj1 中而不存在于 obj2 中,则它应该保持在 obj1 中的状态

标签: javascript ecmascript-6 lodash


【解决方案1】:

如果您想要自定义合并策略,也许您可​​以编写自己的递归函数。在递归函数中,您基本上传入了目标和源。根据您的问题,目标为obj1,源为obj2

你的逻辑是:

  1. 如果obj1 不包含obj2 中的键,我们将保留来自源obj1 的键值对
  2. 如果obj1 包含obj2 的键,则:
    • 如果它们只是非对象,我们允许obj2 值覆盖obj1
    • 如果它们都是对象,那么我们再次调用相同的递归函数

请参阅下面的概念验证:

const obj1 = {
  a1: {
    b1: 2
  },
  a2: 5
}

const obj2 = {
  a1: {
    b1: 4,
    b2: 9
  },
  a3: 6
}

function smartMerge(target, source) {
  const o = {};
  
  // Iterate throught all keys in your target
  for(let k in target) {
  
    // If a matching key is found in source
    if (k in source) {
      // If they are both objects, then we run recurisve merge logic
      if (typeof target[k] === 'object' && typeof source[k] === 'object') {
        o[k] = smartMerge(target[k], source[k]);
      }
      // Otherwise, we let the source override the value
      else {
        o[k] = source[k];
      }
    }
    
    // If no matching key is found, we keep the target value
    else {
      o[k] = target[k];
    }
  }
  
  return o;
}

const result = smartMerge(obj1, obj2);

/* Expected:
{
  a1: {
    b1: 4
  },
  a2: 5
}
*/
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 2014-12-08
    • 2012-09-14
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多