如何深度合并而不是浅合并?

时间:2015-01-14 06:07:35

标签: javascript spread-syntax

Object.assignObject spread都只进行浅层合并。

问题的一个例子:

// No object nesting
const x = { a: 1 }
const y = { b: 1 }
const z = { ...x, ...y } // { a: 1, b: 1 }

输出是您所期望的。但是如果我试试这个:

// Object nesting
const x = { a: { a: 1 } }
const y = { a: { b: 1 } }
const z = { ...x, ...y } // { a: { b: 1 } }

而不是

{ a: { a: 1, b: 1 } }

你得到了

{ a: { b: 1 } }

x被完全覆盖,因为扩展语法只有一个深度。这与Object.assign()相同。

有办法做到这一点吗?

44 个答案:

答案 0 :(得分:287)

  

有人知道ES6 / ES7规范中是否存在深度合并?

不,它没有。

答案 1 :(得分:133)

我知道这是一个老问题,但ES2015 / ES6中我能想到的最简单的解决方案实际上很简单,使用Object.assign(),

希望这会有所帮助:

/**
 * Simple object check.
 * @param item
 * @returns {boolean}
 */
export function isObject(item) {
  return (item && typeof item === 'object' && !Array.isArray(item));
}

/**
 * Deep merge two objects.
 * @param target
 * @param ...sources
 */
export function mergeDeep(target, ...sources) {
  if (!sources.length) return target;
  const source = sources.shift();

  if (isObject(target) && isObject(source)) {
    for (const key in source) {
      if (isObject(source[key])) {
        if (!target[key]) Object.assign(target, { [key]: {} });
        mergeDeep(target[key], source[key]);
      } else {
        Object.assign(target, { [key]: source[key] });
      }
    }
  }

  return mergeDeep(target, ...sources);
}

使用示例:

mergeDeep(this, { a: { b: { c: 123 } } });
// or
const merged = mergeDeep({a: 1}, { b : { c: { d: { e: 12345}}}});  
console.dir(merged); // { a: 1, b: { c: { d: [Object] } } }

您将在下面的答案中找到不可变版本。

请注意,这将导致循环引用无限递归。如果您认为自己面临此问题,那么有关如何检测循环引用的一些很好的答案。

答案 2 :(得分:85)

当涉及到宿主物品或任何比一袋价值更复杂的物品时,这个问题是非常重要的

  • 您是否调用getter来获取值,还是复制属性描述符?
  • 如果合并目标有一个setter(自己的属性或其原型链)怎么办?您是否认为该值已存在或调用setter来更新当前值?
  • 你调用自己的属性函数还是复制它们?如果它们在定义时根据其范围链中的某些内容绑定了函数或箭头函数会怎么样?
  • 如果它像DOM节点那样怎么办?您当然不希望将其视为简单对象,只是将其所有属性深度合并到
  • 如何处理"简单"数组,地图或集合等结构?考虑一下它们已经存在或合并它们吗?
  • 如何处理不可枚举的自有属性?
  • 新的子树怎么样?只需通过引用或深度克隆分配?
  • 如何处理冷冻/密封/不可扩展的物体?

要记住的另一件事:包含循环的对象图。它通常不难处理 - 只需保留Set已访问过的源对象 - 但经常被遗忘。

你可能应该编写一个深度合并函数,它只需要原始值和简单对象 - 最多只有那些structured clone algorithm can handle - 作为合并源的类型。如果它遇到任何它无法处理的东西或只是通过引用分配而不是深度合并,则抛出。

换句话说,没有一个通用算法,你要么自己动手,要么寻找恰好涵盖你的用例的库方法。

答案 3 :(得分:75)

您可以使用Lodash merge

UpdateWindow()

答案 4 :(得分:47)

这是@ Salakar的答案的不可变(不修改输入)版本。如果您正在使用函数式编程类型的东西,这很有用。

export function isObject(item) {
  return (item && typeof item === 'object' && !Array.isArray(item));
}

export default function mergeDeep(target, source) {
  let output = Object.assign({}, target);
  if (isObject(target) && isObject(source)) {
    Object.keys(source).forEach(key => {
      if (isObject(source[key])) {
        if (!(key in target))
          Object.assign(output, { [key]: source[key] });
        else
          output[key] = mergeDeep(target[key], source[key]);
      } else {
        Object.assign(output, { [key]: source[key] });
      }
    });
  }
  return output;
}

答案 5 :(得分:22)

由于此问题仍然有效,这是另一种方法:

  • ES6 / 2015
  • 不可变(不会修改原始对象)
  • 处理数组(连接它们)



/**
* Performs a deep merge of objects and returns new object. Does not modify
* objects (immutable) and merges arrays via concatenation.
*
* @param {...object} objects - Objects to merge
* @returns {object} New object with merged key/values
*/
function mergeDeep(...objects) {
  const isObject = obj => obj && typeof obj === 'object';
  
  return objects.reduce((prev, obj) => {
    Object.keys(obj).forEach(key => {
      const pVal = prev[key];
      const oVal = obj[key];
      
      if (Array.isArray(pVal) && Array.isArray(oVal)) {
        prev[key] = pVal.concat(...oVal);
      }
      else if (isObject(pVal) && isObject(oVal)) {
        prev[key] = mergeDeep(pVal, oVal);
      }
      else {
        prev[key] = oVal;
      }
    });
    
    return prev;
  }, {});
}

// Test objects
const obj1 = {
  a: 1,
  b: 1, 
  c: { x: 1, y: 1 },
  d: [ 1, 1 ]
}
const obj2 = {
  b: 2, 
  c: { y: 2, z: 2 },
  d: [ 2, 2 ],
  e: 2
}
const obj3 = mergeDeep(obj1, obj2);

// Out
console.log(obj3);




答案 6 :(得分:21)

我知道已经有很多答案,并且有很多评论认为他们不会工作。唯一的共识是, 它如此复杂,没有人为它制定标准 。然而,SO中大多数公认的答案暴露了简单的技巧和#34;广泛使用的。因此,对于像我这样没有专家但想通过掌握更多关于javascript复杂性来编写更安全代码的我们所有人,我会试着解释一下。

在弄清楚之前,让我澄清2点:

  • [免责声明]我建议使用下面的函数来解决我们深度循环javascript objects的副本的问题,并说明通常过于简短的评论。它不是生产准备好的。为了清楚起见,我有意不考虑其他注意事项,如circular objects (track by a set or unconflicting symbol property),复制引用值或deep clone,不可变目标对象(深度克隆再次?),{{3}的逐案研究},通过each type of objects获取/设置属性...此外,我没有测试性能 - 尽管它很重要 - 因为它不是重点。
  • 我将使用复制分配条款而不是 merge 。因为在我看来, merge 是保守的,并且应该在发生冲突时失败。在这里,当发生冲突时,我们希望源覆盖目标。就像Object.assign一样。

for..inObject.keys的答案具有误导性

制作深层副本似乎是如此基本和通用的做法,我们希望通过简单的递归找到一个单行或至少快速获胜。我们不希望我们需要一个库或编写100行的自定义函数。

当我第一次阅读accessors时,我真的认为我可以做得更好更简单(您可以将其与Object.assign上的x={a:1}, y={a:{b:1}}进行比较)。然后我读了Salakar's answer并且我认为......没有那么容易逃脱,改善已经得到的答案不会让我们走远。

让我们立即进行深度复制和递归。只要考虑人们如何(错误地)解析属性来复制一个非常简单的对象。

const y = Object.create(
    { proto : 1 },
    { a: { enumerable: true, value: 1},
      [Symbol('b')] : { enumerable: true, value: 1} } )

Object.assign({},y)
> { 'a': 1, Symbol(b): 1 } // All (enumerable) properties are copied

((x,y) => Object.keys(y).reduce((acc,k) => Object.assign(acc, { [k]: y[k] }), x))({},y)
> { 'a': 1 } // Missing a property!

((x,y) => {for (let k in y) x[k]=y[k];return x})({},y)
> { 'a': 1, 'proto': 1 } // Missing a property! Prototype's property is copied too!

Object.keys将省略自己的非可枚举属性,拥有符号键控属性和所有原型属性。如果您的物品没有任何物品,可能会很好。但要记住Object.assign处理自己的符号键可枚举属性。所以你的自定义副本失去了它的绽放。

for..in将提供源,其原型和完整原型链的属性,而无需您(或知道它)。您的目标最终可能会包含太多属性,混合原型属性和属性。

如果您正在编写通用功能,并且未使用Object.getOwnPropertyDescriptorsObject.getOwnPropertyNamesObject.getOwnPropertySymbolsObject.getPrototypeOf,那么您就是这样做的。最可能做错了。

在编写函数之前需要考虑的事项

首先,确保您了解Javascript对象是什么。在Javascript中,对象由其自己的属性和(父)原型对象组成。原型对象又由它自己的属性和原型对象组成。等等,定义原型链。

属性是一对密钥(stringsymbol)和描述符(valueget / set访问者,以及{{{{ 1}})。

最后,有the8472's answer。您可能希望以不同的方式处理来自对象Date或对象Function的对象Object。

因此,编写深层副本时,至少应该回答这些问题:

  1. 我认为什么深(适合递归查找)或扁平?
  2. 我想要复制哪些属性? (可枚举/不可枚举,字符串键控/符号键控,自己的属性/原型'自己的属性,值/描述符......)
  3. 对于我的示例,我认为只有enumerable,因为其他构造函数创建的其他对象可能不适合深入查看。从many types of objects自定义。

    object Object

    我创建了一个function toType(a) { // Get fine type (object, array, function, null, error, date ...) return ({}).toString.call(a).match(/([a-z]+)(:?\])/i)[1]; } function isDeepObject(obj) { return "Object" === toType(obj); } 对象来选择要复制的内容(用于演示目的)。

    options

    提议的职能

    您可以在this SO中进行测试。

    const options = {nonEnum:true, symbols:true, descriptors: true, proto:true};
    

    可以这样使用:

    function deepAssign(options) {
        return function deepAssignWithOptions (target, ...sources) {
            sources.forEach( (source) => {
    
                if (!isDeepObject(source) || !isDeepObject(target))
                    return;
    
                // Copy source's own properties into target's own properties
                function copyProperty(property) {
                    const descriptor = Object.getOwnPropertyDescriptor(source, property);
                    //default: omit non-enumerable properties
                    if (descriptor.enumerable || options.nonEnum) {
                        // Copy in-depth first
                        if (isDeepObject(source[property]) && isDeepObject(target[property]))
                            descriptor.value = deepAssign(options)(target[property], source[property]);
                        //default: omit descriptors
                        if (options.descriptors)
                            Object.defineProperty(target, property, descriptor); // shallow copy descriptor
                        else
                            target[property] = descriptor.value; // shallow copy value only
                    }
                }
    
                // Copy string-keyed properties
                Object.getOwnPropertyNames(source).forEach(copyProperty);
    
                //default: omit symbol-keyed properties
                if (options.symbols)
                    Object.getOwnPropertySymbols(source).forEach(copyProperty);
    
                //default: omit prototype's own properties
                if (options.proto)
                    // Copy souce prototype's own properties into target prototype's own properties
                    deepAssign(Object.assign({},options,{proto:false})) (// Prevent deeper copy of the prototype chain
                        Object.getPrototypeOf(target),
                        Object.getPrototypeOf(source)
                    );
    
            });
            return target;
        }
    }
    

答案 7 :(得分:8)

在这里,直截了当;

一种简单的解决方案,其作用类似于Object.assign,并且无需修改即可用于数组。

function deepAssign(target, ...sources) {
  for (source of sources) {
    for (let k in source) {
      let vs = source[k], vt = target[k]
      if (Object(vs) == vs && Object(vt) === vt) {
        target[k] = deepAssign(vt, vs)
        continue
      }
      target[k] = source[k]
    }
  }
  return target
}

x = { a: { a: 1 }, b: [1,2] }
y = { a: { b: 1 }, b: [3] }
z = { c: 3, b: [,,,4] }
x = deepAssign(x, y, z)

console.log(JSON.stringify(x) === JSON.stringify({
  "a": {
    "a": 1,
    "b": 1
  },
  "b": [ 1, 2, null, 4 ],
  "c": 3
}))

答案 8 :(得分:8)

这是TypeScript实现:

export const mergeObjects = <T extends object = object>(target: T, ...sources: T[]): T  => {
  if (!sources.length) {
    return target;
  }
  const source = sources.shift();
  if (source === undefined) {
    return target;
  }

  if (isMergebleObject(target) && isMergebleObject(source)) {
    Object.keys(source).forEach(function(key: string) {
      if (isMergebleObject(source[key])) {
        if (!target[key]) {
          target[key] = {};
        }
        mergeObjects(target[key], source[key]);
      } else {
        target[key] = source[key];
      }
    });
  }

  return mergeObjects(target, ...sources);
};

const isObject = (item: any): boolean => {
  return item !== null && typeof item === 'object';
};

const isMergebleObject = (item): boolean => {
  return isObject(item) && !Array.isArray(item);
};

单元测试:

describe('merge', () => {
  it('should merge Objects and all nested Ones', () => {
    const obj1 = { a: { a1: 'A1'}, c: 'C', d: {} };
    const obj2 = { a: { a2: 'A2'}, b: { b1: 'B1'}, d: null };
    const obj3 = { a: { a1: 'A1', a2: 'A2'}, b: { b1: 'B1'}, c: 'C', d: null};
    expect(mergeObjects({}, obj1, obj2)).toEqual(obj3);
  });
  it('should behave like Object.assign on the top level', () => {
    const obj1 = { a: { a1: 'A1'}, c: 'C'};
    const obj2 = { a: undefined, b: { b1: 'B1'}};
    expect(mergeObjects({}, obj1, obj2)).toEqual(Object.assign({}, obj1, obj2));
  });
  it('should not merge array values, just override', () => {
    const obj1 = {a: ['A', 'B']};
    const obj2 = {a: ['C'], b: ['D']};
    expect(mergeObjects({}, obj1, obj2)).toEqual({a: ['C'], b: ['D']});
  });
  it('typed merge', () => {
    expect(mergeObjects<TestPosition>(new TestPosition(0, 0), new TestPosition(1, 1)))
      .toEqual(new TestPosition(1, 1));
  });
});

class TestPosition {
  constructor(public x: number = 0, public y: number = 0) {/*empty*/}
}

答案 9 :(得分:7)

如果您使用的是ImmutableJS,则可以使用mergeDeep

fromJS(options).mergeDeep(options2).toJS();

答案 10 :(得分:6)

deepmerge npm软件包似乎是解决此问题最广泛使用的库: https://www.npmjs.com/package/deepmerge

答案 11 :(得分:6)

我用lodash:

import _ = require('lodash');
value = _.merge(value1, value2);

答案 12 :(得分:6)

我想介绍一个非常简单的ES5替代方案。该函数有两个参数 - targetsource,必须是“object”类型。 Target将成为结果对象。 Target保留所有原始属性,但可以修改它们的值。

function deepMerge(target, source) {
if(typeof target !== 'object' || typeof source !== 'object') return false; // target or source or both ain't objects, merging doesn't make sense
for(var prop in source) {
  if(!source.hasOwnProperty(prop)) continue; // take into consideration only object's own properties.
  if(prop in target) { // handling merging of two properties with equal names
    if(typeof target[prop] !== 'object') {
      target[prop] = source[prop];
    } else {
      if(typeof source[prop] !== 'object') {
        target[prop] = source[prop];
      } else {
        if(target[prop].concat && source[prop].concat) { // two arrays get concatenated
          target[prop] = target[prop].concat(source[prop]);
        } else { // two objects get merged recursively
          target[prop] = deepMerge(target[prop], source[prop]); 
        } 
      }  
    }
  } else { // new properties get added to target
    target[prop] = source[prop]; 
  }
}
return target;
}

<强>例:

  • 如果target没有source属性,则target获取该属性;
  • 如果target确实有source属性且target&amp; source不是 两个对象(4个中的3个),target的属性被覆盖;
  • 如果target确实有source属性,并且它们都是对象/数组(其余1个),那么合并两个对象(或两个数组的连接)会发生递归;

还要考虑以下

  1. array + obj = array
  2. obj + array = obj
  3. obj + obj = obj(递归合并)
  4. array + array = array(concat)
  5. 它是可预测的,支持原始类型以及数组和对象。另外,由于我们可以合并2个对象,我认为我们可以通过reduce函数合并2个以上的对象。

    看一个例子(如果你愿意的话,可以玩它)

    var a = {
       "a_prop": 1,
       "arr_prop": [4, 5, 6],
       "obj": {
         "a_prop": {
           "t_prop": 'test'
         },
         "b_prop": 2
       }
    };
    
    var b = {
       "a_prop": 5,
       "arr_prop": [7, 8, 9],
       "b_prop": 15,
       "obj": {
         "a_prop": {
           "u_prop": false
         },
         "b_prop": {
            "s_prop": null
         }
       }
    };
    
    function deepMerge(target, source) {
        if(typeof target !== 'object' || typeof source !== 'object') return false;
        for(var prop in source) {
        if(!source.hasOwnProperty(prop)) continue;
          if(prop in target) {
            if(typeof target[prop] !== 'object') {
              target[prop] = source[prop];
            } else {
              if(typeof source[prop] !== 'object') {
                target[prop] = source[prop];
              } else {
                if(target[prop].concat && source[prop].concat) {
                  target[prop] = target[prop].concat(source[prop]);
                } else {
                  target[prop] = deepMerge(target[prop], source[prop]); 
                } 
              }  
            }
          } else {
            target[prop] = source[prop]; 
          }
        }
      return target;
    }
    
    console.log(deepMerge(a, b));

    有一个限制 - 浏览器的调用堆栈长度。现代浏览器会在一些非常深层次的递归中抛出错误(想想成千上万的嵌套调用)。此外,您可以通过添加新条件和类型检查来自由地处理数组+对象等情况。

答案 13 :(得分:6)

这是另一个ES6解决方案,适用于对象和数组。

function deepMerge(...sources) {
  let acc = {}
  for (const source of sources) {
    if (source instanceof Array) {
      if (!(acc instanceof Array)) {
        acc = []
      }
      acc = [...acc, ...source]
    } else if (source instanceof Object) {
      for (let [key, value] of Object.entries(source)) {
        if (value instanceof Object && key in acc) {
          value = deepMerge(acc[key], value)
        }
        acc = { ...acc, [key]: value }
      }
    }
  }
  return acc
}

答案 14 :(得分:5)

以下函数制作对象的深层副本,它包括复制基元,数组和对象

 function mergeDeep (target, source)  {
    if (typeof target == "object" && typeof source == "object") {
        for (const key in source) {
            if (source[key] === null && (target[key] === undefined || target[key] === null)) {
                target[key] = null;
            } else if (source[key] instanceof Array) {
                if (!target[key]) target[key] = [];
                //concatenate arrays
                target[key] = target[key].concat(source[key]);
            } else if (typeof source[key] == "object") {
                if (!target[key]) target[key] = {};
                this.mergeDeep(target[key], source[key]);
            } else {
                target[key] = source[key];
            }
        }
    }
    return target;
}

答案 15 :(得分:4)

  

有没有办法做到这一点?

如果 npm库可以用作解决方案,那么您的object-merge-advanced确实允许深度合并对象,并使用熟悉的回调函数自定义/覆盖每个合并操作。它的主要思想不只是深度合并-当两个键相同时,值会发生什么?该库负责解决这一问题-当两个键发生冲突时,object-merge-advanced会权衡类型,目的是在合并后保留尽可能多的数据:

object key merging weighing key value types to retain as much data as possible

第一个输入自变量的键被标记为#1,第二个自变量的键被标记为#2。根据每种类型,选择一个作为结果键的值。在图中,“对象”表示一个普通对象(不是数组等)。

当按键不冲突时,它们都会输入结果。

从示例代码段开始,如果您使用object-merge-advanced合并代码段:

const mergeObj = require("object-merge-advanced");
const x = { a: { a: 1 } };
const y = { a: { b: 1 } };
const res = console.log(mergeObj(x, y));
// => res = {
//      a: {
//        a: 1,
//        b: 1
//      }
//    }

该算法递归地遍历所有输入对象键,进行比较并生成并返回新的合并结果。

答案 16 :(得分:3)

使用ES5的简单解决方案(覆盖现有值):

function merge(current, update) {
  Object.keys(update).forEach(function(key) {
    // if update[key] exist, and it's not a string or array,
    // we go in one level deeper
    if (current.hasOwnProperty(key) 
        && typeof current[key] === 'object'
        && !(current[key] instanceof Array)) {
      merge(current[key], update[key]);

    // if update[key] doesn't exist in current, or it's a string
    // or array, then assign/overwrite current[key] to update[key]
    } else {
      current[key] = update[key];
    }
  });
  return current;
}

var x = { a: { a: 1 } }
var y = { a: { b: 1 } }

console.log(merge(x, y));

答案 17 :(得分:3)

加载缓存的redux状态时遇到了这个问题。如果我只是加载缓存状态,我会为具有更新状态结构的新应用版本遇到错误。

已经提到过,lodash提供了我使用的merge函数:

const currentInitialState = configureState().getState();
const mergedState = _.merge({}, currentInitialState, cachedState);
const store = configureState(mergedState);

答案 18 :(得分:3)

我们可以使用 $ .extend(true,object1,object2)进行深度合并。值 true 表示递归合并两个对象,修改第一个。

$extend(true,target,object)

答案 19 :(得分:2)

这是我刚才写的另一个支持数组的。它汇总了他们。

function isObject(obj) {
    return obj !== null && typeof obj === 'object';
}


function isPlainObject(obj) {
    return isObject(obj) && (
        obj.constructor === Object  // obj = {}
        || obj.constructor === undefined // obj = Object.create(null)
    );
}

function mergeDeep(target, ...sources) {
    if (!sources.length) return target;
    const source = sources.shift();

    if(Array.isArray(target)) {
        if(Array.isArray(source)) {
            target.push(...source);
        } else {
            target.push(source);
        }
    } else if(isPlainObject(target)) {
        if(isPlainObject(source)) {
            for(let key of Object.keys(source)) {
                if(!target[key]) {
                    target[key] = source[key];
                } else {
                    mergeDeep(target[key], source[key]);
                }
            }
        } else {
            throw new Error(`Cannot merge object with non-object`);
        }
    } else {
        target = source;
    }

    return mergeDeep(target, ...sources);
};

答案 20 :(得分:2)

使用此功能:

merge(target, source, mutable = false) {
        const newObj = typeof target == 'object' ? (mutable ? target : Object.assign({}, target)) : {};
        for (const prop in source) {
            if (target[prop] == null || typeof target[prop] === 'undefined') {
                newObj[prop] = source[prop];
            } else if (Array.isArray(target[prop])) {
                newObj[prop] = source[prop] || target[prop];
            } else if (target[prop] instanceof RegExp) {
                newObj[prop] = source[prop] || target[prop];
            } else {
                newObj[prop] = typeof source[prop] === 'object' ? this.merge(target[prop], source[prop]) : source[prop];
            }
        }
        return newObj;
    }

答案 21 :(得分:1)

减少

export const merge = (objFrom, objTo) => Object.keys(objFrom)
    .reduce(
        (merged, key) => {
            merged[key] = objFrom[key] instanceof Object && !Array.isArray(objFrom[key])
                ? merge(objFrom[key], merged[key] ?? {})
                : objFrom[key]
            return merged
        }, { ...objTo }
    )
test('merge', async () => {
    const obj1 = { par1: -1, par2: { par2_1: -21, par2_5: -25 }, arr: [0,1,2] }
    const obj2 = { par1: 1, par2: { par2_1: 21 }, par3: 3, arr: [3,4,5] }
    const obj3 = merge3(obj1, obj2)
    expect(obj3).toEqual(
        { par1: -1, par2: { par2_1: -21, par2_5: -25 }, par3: 3, arr: [0,1,2] }
    )
})

答案 22 :(得分:1)

如果您想要一个衬纸而不需要像lodash这样的巨大库,建议您使用deepmerge。 (list_1 =[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] list_2 =[]

然后,您可以

npm install deepmerge

获取

deepmerge({ a: 1, b: 2, c: 3 }, { a: 2, d: 3 });

令人高兴的是,它随带TypeScript键入功能。

答案 23 :(得分:1)

Ramda是一个很好的javascript函数库,具有mergeDeepLeft和mergeDeepRight。这些方法都可以很好地解决此问题。请在此处查看文档:{​​{3}}

对于有问题的特定示例,我们可以使用:

import { mergeDeepLeft } from 'ramda'
const x = { a: { a: 1 } }
const y = { a: { b: 1 } }
const z = mergeDeepLeft(x, y)) // {"a":{"a":1,"b":1}}

答案 24 :(得分:1)

这里的大多数示例似乎太复杂了,我在我创建的TypeScript中使用了一个示例,我认为它应该涵盖大多数情况(我将数组作为常规数据进行处理,只是替换它们)。

const isObject = (item: any) => typeof item === 'object' && !Array.isArray(item);

export const merge = <A = Object, B = Object>(target: A, source: B): A & B => {
  const isDeep = (prop: string) =>
    isObject(source[prop]) && target.hasOwnProperty(prop) && isObject(target[prop]);
  const replaced = Object.getOwnPropertyNames(source)
    .map(prop => ({ [prop]: isDeep(prop) ? merge(target[prop], source[prop]) : source[prop] }))
    .reduce((a, b) => ({ ...a, ...b }), {});

  return {
    ...(target as Object),
    ...(replaced as Object)
  } as A & B;
};

与普通JS相同,以防万一:

const isObject = item => typeof item === 'object' && !Array.isArray(item);

const merge = (target, source) => {
  const isDeep = prop => 
    isObject(source[prop]) && target.hasOwnProperty(prop) && isObject(target[prop]);
  const replaced = Object.getOwnPropertyNames(source)
    .map(prop => ({ [prop]: isDeep(prop) ? merge(target[prop], source[prop]) : source[prop] }))
    .reduce((a, b) => ({ ...a, ...b }), {});

  return {
    ...target,
    ...replaced
  };
};

这是我的测试用例,以展示您如何使用它

describe('merge', () => {
  context('shallow merges', () => {
    it('merges objects', () => {
      const a = { a: 'discard' };
      const b = { a: 'test' };
      expect(merge(a, b)).to.deep.equal({ a: 'test' });
    });
    it('extends objects', () => {
      const a = { a: 'test' };
      const b = { b: 'test' };
      expect(merge(a, b)).to.deep.equal({ a: 'test', b: 'test' });
    });
    it('extends a property with an object', () => {
      const a = { a: 'test' };
      const b = { b: { c: 'test' } };
      expect(merge(a, b)).to.deep.equal({ a: 'test', b: { c: 'test' } });
    });
    it('replaces a property with an object', () => {
      const a = { b: 'whatever', a: 'test' };
      const b = { b: { c: 'test' } };
      expect(merge(a, b)).to.deep.equal({ a: 'test', b: { c: 'test' } });
    });
  });

  context('deep merges', () => {
    it('merges objects', () => {
      const a = { test: { a: 'discard', b: 'test' }  };
      const b = { test: { a: 'test' } } ;
      expect(merge(a, b)).to.deep.equal({ test: { a: 'test', b: 'test' } });
    });
    it('extends objects', () => {
      const a = { test: { a: 'test' } };
      const b = { test: { b: 'test' } };
      expect(merge(a, b)).to.deep.equal({ test: { a: 'test', b: 'test' } });
    });
    it('extends a property with an object', () => {
      const a = { test: { a: 'test' } };
      const b = { test: { b: { c: 'test' } } };
      expect(merge(a, b)).to.deep.equal({ test: { a: 'test', b: { c: 'test' } } });
    });
    it('replaces a property with an object', () => {
      const a = { test: { b: 'whatever', a: 'test' } };
      const b = { test: { b: { c: 'test' } } };
      expect(merge(a, b)).to.deep.equal({ test: { a: 'test', b: { c: 'test' } } });
    });
  });
});

如果您认为我缺少某些功能,请告诉我。

答案 25 :(得分:1)

有一个lodash软件包,专门用于深度克隆对象。优点是您不必包括整个lodash库。

它叫lodash.clonedeep

在nodejs中,用法是这样的

var cloneDeep = require('lodash.clonedeep');
 
const newObject = cloneDeep(oldObject);

在ReactJS中,用法是

import cloneDeep from 'lodash/cloneDeep';

const newObject = cloneDeep(oldObject);

检查文档here。如果您对它的工作方式感兴趣,请查看源文件here

答案 26 :(得分:1)

https://lodash.com/docs/4.17.15#defaultsDeep

注意:此方法会变异来源。

_.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });
// => { 'a': { 'b': 2, 'c': 3 } }

答案 27 :(得分:1)

有时你不需要深度合并,即使你是这么认为的。例如,如果您有一个带有嵌套对象的默认配置,并且您希望使用自己的配置对其进行深度扩展,则可以为其创建一个类。这个概念非常简单:

function AjaxConfig(config) {

  // Default values + config

  Object.assign(this, {
    method: 'POST',
    contentType: 'text/plain'
  }, config);

  // Default values in nested objects

  this.headers = Object.assign({}, this.headers, { 
    'X-Requested-With': 'custom'
  });
}

// Define your config

var config = {
  url: 'https://google.com',
  headers: {
    'x-client-data': 'CI22yQEI'
  }
};

// Extend the default values with your own
var fullMergedConfig = new AjaxConfig(config);

// View in DevTools
console.log(fullMergedConfig);

您可以将其转换为函数(不是构造函数)。

答案 28 :(得分:0)

使用实用程序“ deepmerge”(link)或此处的代码:LINK,效果很好

答案 29 :(得分:0)

另一种使用递归的变体,希望对您有用。

const merge = (obj1, obj2) => {

    const recursiveMerge = (obj, entries) => {
         for (const [key, value] of entries) {
            if (typeof value === "object") {
               obj[key] = obj[key] ? {...obj[key]} : {};
               recursiveMerge(obj[key], Object.entries(value))
            else {
               obj[key] = value;
            }
          }

          return obj;
    }

    return recursiveMerge(obj1, Object.entries(obj2))
}

答案 30 :(得分:0)

我发现只有2行解决方案可以在javascript中进行深度合并。让我知道这对您有何帮助。

const obj1 = { a: { b: "c", x: "y" } }
const obj2 = { a: { b: "d", e: "f" } }
temp = Object.assign({}, obj1, obj2)
Object.keys(temp).forEach(key => {
    temp[key] = (typeof temp[key] === 'object') ? Object.assign(temp[key], obj1[key], obj2[key]) : temp[key])
}
console.log(temp)

临时对象将打印{a:{b:'d',e:'f',x:'y'}}

答案 31 :(得分:0)

我的用例是将默认值合并到配置中。如果我的组件接受具有深层嵌套结构的配置对象,并且我的组件定义了默认配置,那么我想在我的配置中为所有未提供的配置选项设置默认值。

用法示例:

export default MyComponent = ({config}) => {
  const mergedConfig = mergeDefaults(config, {header:{margins:{left:10, top: 10}}});
  // Component code here
}

这使我可以传递一个空的或空的配置,或部分配置,并使所有未配置的值都恢复为默认值。

我对mergeDefaults的实现如下所示:

export default function mergeDefaults(config, defaults) {
  if (config === null || config === undefined) return defaults;
  for (var attrname in defaults) {
    if (defaults[attrname].constructor === Object) config[attrname] = mergeDefaults(config[attrname], defaults[attrname]);
    else if (config[attrname] === undefined) config[attrname] = defaults[attrname];
  }
  return config;
}


这些是我的单元测试

import '@testing-library/jest-dom/extend-expect';
import mergeDefaults from './mergeDefaults';

describe('mergeDefaults', () => {
  it('should create configuration', () => {
    const config = mergeDefaults(null, { a: 10, b: { c: 'default1', d: 'default2' } });
    expect(config.a).toStrictEqual(10);
    expect(config.b.c).toStrictEqual('default1');
    expect(config.b.d).toStrictEqual('default2');
  });
  it('should fill configuration', () => {
    const config = mergeDefaults({}, { a: 10, b: { c: 'default1', d: 'default2' } });
    expect(config.a).toStrictEqual(10);
    expect(config.b.c).toStrictEqual('default1');
    expect(config.b.d).toStrictEqual('default2');
  });
  it('should not overwrite configuration', () => {
    const config = mergeDefaults({ a: 12, b: { c: 'config1', d: 'config2' } }, { a: 10, b: { c: 'default1', d: 'default2' } });
    expect(config.a).toStrictEqual(12);
    expect(config.b.c).toStrictEqual('config1');
    expect(config.b.d).toStrictEqual('config2');
  });
  it('should merge configuration', () => {
    const config = mergeDefaults({ a: 12, b: { d: 'config2' } }, { a: 10, b: { c: 'default1', d: 'default2' }, e: 15 });
    expect(config.a).toStrictEqual(12);
    expect(config.b.c).toStrictEqual('default1');
    expect(config.b.d).toStrictEqual('config2');
    expect(config.e).toStrictEqual(15);
  });
});

答案 32 :(得分:0)

这是一种便宜的深度合并,它使用我想不到的代码。每个来源都将覆盖先前的属性。

const { keys } = Object;

const isObject = a => typeof a === "object" && !Array.isArray(a);
const merge = (a, b) =>
  isObject(a) && isObject(b)
    ? deepMerge(a, b)
    : isObject(a) && !isObject(b)
    ? a
    : b;

const coalesceByKey = source => (acc, key) =>
  (acc[key] && source[key]
    ? (acc[key] = merge(acc[key], source[key]))
    : (acc[key] = source[key])) && acc;

/**
 * Merge all sources into the target
 * overwriting primitive values in the the accumulated target as we go (if they already exist)
 * @param {*} target
 * @param  {...any} sources
 */
const deepMerge = (target, ...sources) =>
  sources.reduce(
    (acc, source) => keys(source).reduce(coalesceByKey(source), acc),
    target
  );

console.log(deepMerge({ a: 1 }, { a: 2 }));
console.log(deepMerge({ a: 1 }, { a: { b: 2 } }));
console.log(deepMerge({ a: { b: 2 } }, { a: 1 }));

答案 33 :(得分:0)

我正在使用以下简短函数来深度合并对象。
对我来说很棒。
The author completely explains how it works here.

/*!
 * Merge two or more objects together.
 * (c) 2017 Chris Ferdinandi, MIT License, https://gomakethings.com
 * @param   {Boolean}  deep     If true, do a deep (or recursive) merge [optional]
 * @param   {Object}   objects  The objects to merge together
 * @returns {Object}            Merged values of defaults and options
 * 
 * Use the function as follows:
 * let shallowMerge = extend(obj1, obj2);
 * let deepMerge = extend(true, obj1, obj2)
 */

var extend = function () {

    // Variables
    var extended = {};
    var deep = false;
    var i = 0;

    // Check if a deep merge
    if ( Object.prototype.toString.call( arguments[0] ) === '[object Boolean]' ) {
        deep = arguments[0];
        i++;
    }

    // Merge the object into the extended object
    var merge = function (obj) {
        for (var prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                // If property is an object, merge properties
                if (deep && Object.prototype.toString.call(obj[prop]) === '[object Object]') {
                    extended[prop] = extend(extended[prop], obj[prop]);
                } else {
                    extended[prop] = obj[prop];
                }
            }
        }
    };

    // Loop through each object and conduct a merge
    for (; i < arguments.length; i++) {
        merge(arguments[i]);
    }

    return extended;

};

答案 34 :(得分:0)

许多答案使用数十行代码,或者需要向项目中添加新库,但是如果使用递归,则只需四行代码。

function merge(current, updates) {
  for (key of Object.keys(updates)) {
    if (!current.hasOwnProperty(key) || typeof updates[key] !== 'object') current[key] = updates[key];
    else merge(current[key], updates[key]);
  }
  return current;
}
console.log(merge({ a: { a: 1 } }, { a: { b: 1 } }));

数组处理:上面的版本用新的覆盖旧的数组值。如果您希望它保留旧的数组值并添加新的值,只需在else if (current[key] instanceof Array && updates[key] instanceof Array) current[key] = current[key].concat(updates[key])语句上方添加一个else块就可以了。

答案 35 :(得分:0)

用例:合并默认配置

如果我们以以下形式定义配置:

const defaultConf = {
    prop1: 'config1',
    prop2: 'config2'
}

我们可以通过以下方式定义更具体的配置:

const moreSpecificConf = {
    ...defaultConf,
    prop3: 'config3'
}

但是,如果这些配置包含嵌套结构,则此方法将不再起作用。

因此,我编写了一个仅合并{ key: value, ... }意义上的对象并替换其余对象的函数。

const isObject = (val) => val === Object(val);

const merge = (...objects) =>
    objects.reduce(
        (obj1, obj2) => ({
            ...obj1,
            ...obj2,
            ...Object.keys(obj2)
                .filter((key) => key in obj1 && isObject(obj1[key]) && isObject(obj2[key]))
                .map((key) => ({[key]: merge(obj1[key], obj2[key])}))
                .reduce((n1, n2) => ({...n1, ...n2}), {})
        }),
        {}
    );

答案 36 :(得分:0)

// copies all properties from source object to dest object recursively
export function recursivelyMoveProperties(source, dest) {
  for (const prop in source) {
    if (!source.hasOwnProperty(prop)) {
      continue;
    }

    if (source[prop] === null) {
      // property is null
      dest[prop] = source[prop];
      continue;
    }

    if (typeof source[prop] === 'object') {
      // if property is object let's dive into in
      if (Array.isArray(source[prop])) {
        dest[prop] = [];
      } else {
        if (!dest.hasOwnProperty(prop)
        || typeof dest[prop] !== 'object'
        || dest[prop] === null || Array.isArray(dest[prop])
        || !Object.keys(dest[prop]).length) {
          dest[prop] = {};
        }
      }
      recursivelyMoveProperties(source[prop], dest[prop]);
      continue;
    }

    // property is simple type: string, number, e.t.c
    dest[prop] = source[prop];
  }
  return dest;
}

单元测试:

describe('recursivelyMoveProperties', () => {
    it('should copy properties correctly', () => {
      const source: any = {
        propS1: 'str1',
        propS2: 'str2',
        propN1: 1,
        propN2: 2,
        propA1: [1, 2, 3],
        propA2: [],
        propB1: true,
        propB2: false,
        propU1: null,
        propU2: null,
        propD1: undefined,
        propD2: undefined,
        propO1: {
          subS1: 'sub11',
          subS2: 'sub12',
          subN1: 11,
          subN2: 12,
          subA1: [11, 12, 13],
          subA2: [],
          subB1: false,
          subB2: true,
          subU1: null,
          subU2: null,
          subD1: undefined,
          subD2: undefined,
        },
        propO2: {
          subS1: 'sub21',
          subS2: 'sub22',
          subN1: 21,
          subN2: 22,
          subA1: [21, 22, 23],
          subA2: [],
          subB1: false,
          subB2: true,
          subU1: null,
          subU2: null,
          subD1: undefined,
          subD2: undefined,
        },
      };
      let dest: any = {
        propS2: 'str2',
        propS3: 'str3',
        propN2: -2,
        propN3: 3,
        propA2: [2, 2],
        propA3: [3, 2, 1],
        propB2: true,
        propB3: false,
        propU2: 'not null',
        propU3: null,
        propD2: 'defined',
        propD3: undefined,
        propO2: {
          subS2: 'inv22',
          subS3: 'sub23',
          subN2: -22,
          subN3: 23,
          subA2: [5, 5, 5],
          subA3: [31, 32, 33],
          subB2: false,
          subB3: true,
          subU2: 'not null --- ',
          subU3: null,
          subD2: ' not undefined ----',
          subD3: undefined,
        },
        propO3: {
          subS1: 'sub31',
          subS2: 'sub32',
          subN1: 31,
          subN2: 32,
          subA1: [31, 32, 33],
          subA2: [],
          subB1: false,
          subB2: true,
          subU1: null,
          subU2: null,
          subD1: undefined,
          subD2: undefined,
        },
      };
      dest = recursivelyMoveProperties(source, dest);

      expect(dest).toEqual({
        propS1: 'str1',
        propS2: 'str2',
        propS3: 'str3',
        propN1: 1,
        propN2: 2,
        propN3: 3,
        propA1: [1, 2, 3],
        propA2: [],
        propA3: [3, 2, 1],
        propB1: true,
        propB2: false,
        propB3: false,
        propU1: null,
        propU2: null,
        propU3: null,
        propD1: undefined,
        propD2: undefined,
        propD3: undefined,
        propO1: {
          subS1: 'sub11',
          subS2: 'sub12',
          subN1: 11,
          subN2: 12,
          subA1: [11, 12, 13],
          subA2: [],
          subB1: false,
          subB2: true,
          subU1: null,
          subU2: null,
          subD1: undefined,
          subD2: undefined,
        },
        propO2: {
          subS1: 'sub21',
          subS2: 'sub22',
          subS3: 'sub23',
          subN1: 21,
          subN2: 22,
          subN3: 23,
          subA1: [21, 22, 23],
          subA2: [],
          subA3: [31, 32, 33],
          subB1: false,
          subB2: true,
          subB3: true,
          subU1: null,
          subU2: null,
          subU3: null,
          subD1: undefined,
          subD2: undefined,
          subD3: undefined,
        },
        propO3: {
          subS1: 'sub31',
          subS2: 'sub32',
          subN1: 31,
          subN2: 32,
          subA1: [31, 32, 33],
          subA2: [],
          subB1: false,
          subB2: true,
          subU1: null,
          subU2: null,
          subD1: undefined,
          subD2: undefined,
        },
      });
    });
  });

答案 37 :(得分:0)

  

有人知道ES6 / ES7规范中是否存在深度合并?

Object.assign documentation表明它没有做深度克隆。

答案 38 :(得分:0)

维护良好的库已经完成了这项工作。 npm注册表的一个示例是merge-deep

答案 39 :(得分:0)

function isObject(obj) {
    return obj !== null && typeof obj === 'object';
}
const isArray = Array.isArray;

function isPlainObject(obj) {
    return isObject(obj) && (
        obj.constructor === Object  // obj = {}
        || obj.constructor === undefined // obj = Object.create(null)
    );
}

function mergeDeep(target, ...sources){
    if (!sources.length) return target;
    const source = sources.shift();

    if (isPlainObject(source) || isArray(source)) {
        for (const key in source) {
            if (isPlainObject(source[key]) || isArray(source[key])) {
                if (isPlainObject(source[key]) && !isPlainObject(target[key])) {
                    target[key] = {};
                }else if (isArray(source[key]) && !isArray(target[key])) {
                    target[key] = [];
                }
                mergeDeep(target[key], source[key]);
            } else if (source[key] !== undefined && source[key] !== '') {
                target[key] = source[key];
            }
        }
    }

    return mergeDeep(target, ...sources);
}

// test...
var source = {b:333};
var source2 = {c:32, arr: [33,11]}
var n = mergeDeep({a:33}, source, source2);
source2.arr[1] = 22;
console.log(n.arr); // out: [33, 11]

答案 40 :(得分:-1)

我使用es6为深度赋值创建此方法。

function isObject(item) {
  return (item && typeof item === 'object' && !Array.isArray(item) && item !== null)
}

function deepAssign(...objs) {
    if (objs.length < 2) {
        throw new Error('Need two or more objects to merge')
    }

    const target = objs[0]
    for (let i = 1; i < objs.length; i++) {
        const source = objs[i]
        Object.keys(source).forEach(prop => {
            const value = source[prop]
            if (isObject(value)) {
                if (target.hasOwnProperty(prop) && isObject(target[prop])) {
                    target[prop] = deepAssign(target[prop], value)
                } else {
                    target[prop] = value
                }
            } else if (Array.isArray(value)) {
                if (target.hasOwnProperty(prop) && Array.isArray(target[prop])) {
                    const targetArray = target[prop]
                    value.forEach((sourceItem, itemIndex) => {
                        if (itemIndex < targetArray.length) {
                            const targetItem = targetArray[itemIndex]

                            if (Object.is(targetItem, sourceItem)) {
                                return
                            }

                            if (isObject(targetItem) && isObject(sourceItem)) {
                                targetArray[itemIndex] = deepAssign(targetItem, sourceItem)
                            } else if (Array.isArray(targetItem) && Array.isArray(sourceItem)) {
                                targetArray[itemIndex] = deepAssign(targetItem, sourceItem)
                            } else {
                                targetArray[itemIndex] = sourceItem
                            }
                        } else {
                            targetArray.push(sourceItem)
                        }
                    })
                } else {
                    target[prop] = value
                }
            } else {
                target[prop] = value
            }
        })
    }

    return target
}

答案 41 :(得分:-1)

它不存在,但您可以使用JSON.parse(JSON.stringify(jobs))

答案 42 :(得分:-1)

我尝试写Object.assignDeep,这是基于mdnObject.assign的pollyfill。

(ES5)

Object.assignDeep = function (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 = Object(target);

    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(nextSource, nextKey)) {
                    if (typeof to[nextKey] === 'object' 
                        && to[nextKey] 
                        && typeof nextSource[nextKey] === 'object' 
                        && nextSource[nextKey]) {                        
                        Object.assignDeep(to[nextKey], nextSource[nextKey]);
                    } else {
                        to[nextKey] = nextSource[nextKey];
                    }
                }
            }
        }
    }
    return to;
};
console.log(Object.assignDeep({},{a:{b:{c:1,d:1}}},{a:{b:{c:2,e:2}}}))

答案 43 :(得分:-4)

这很简单,有效:

let item = {
    firstName: 'Jonnie',
    lastName: 'Walker',
    fullName: function fullName() {
            return 'Jonnie Walker';
    }
Object.assign(Object.create(item), item);

说明:

Object.create()创建新对象。如果将params传递给函数,它将使用其他对象的原型创建对象。因此,如果你在对象原型上有任何函数,它们将被传递给其他对象的原型。

Object.assign()合并两个对象并创建全新对象,它们不再有引用。所以这个例子对我有用。