通过保留相同键es6的所有值来合并地图(嵌套地图)的地图

时间:2016-10-19 16:31:05

标签: javascript lodash

我正在尝试合并2个具有键和值的地图(又是地图)。

_。合并适用于2个常规地图,但不适用于地图或嵌套地图。

map1 = {k1: {c1: v1, c2: v2}, k2: {c1: v1, c2: v2}};
map2 = {k1: {c3: v3, c4: v4}, k2: {c3: v3, c4: v4}};

期待

mergedMap = {k1: {c1: v1, c2: v2, c3: v3, c4: v4}, k2: {c1: v1, c2: v2, c3: v3, c4: v4}};

1 个答案:

答案 0 :(得分:2)

递归使用_.mergeWith()

ES6解决方案:

const recursiveMerge = (...args) =>
  _.mergeWith({}, ...args, (objValue, srcValue) => {
    if(typeof srcValue === 'object') {
      return recursiveMerge(objValue, srcValue);
    }
  });

const map1 = {k1: {c1: 'v1', c2: 'v2'}, k2: {c1: 'v1', c2: 'v2'}};
const map2 = {k1: {c3: 'v3', c4: 'v4'}, k2: {c3: 'v3', c4: 'v4'}};

const result = recursiveMerge(map1, map2);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>

ES5解决方案:

function recursiveMerge() {
  var args = [].slice.call(arguments, 0);
  var params = [{}].concat(args).concat([
    function(objValue, rcValue) {
      if (typeof srcValue === 'object') {
        return recursiveMerge(objValue, srcValue);
      }
    }]);

  return _.mergeWith.apply(_, params);
}

var map1 = {k1: {c1: 'v1', c2: 'v2'}, k2: {c1: 'v1', c2: 'v2'}};
var map2 = {k1: {c3: 'v3', c4: 'v4'}, k2: {c3: 'v3', c4: 'v4'}};

var result = recursiveMerge(map1, map2);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>