From c250aa804a759d5e446aeb71d3de048d49d826e1 Mon Sep 17 00:00:00 2001 From: jdalton Date: Thu, 19 Mar 2015 08:58:56 -0700 Subject: [PATCH] Ensure `_.merge` correctly coerces objects to arrays. [closes #1061] --- lodash.src.js | 2 +- test/test.js | 18 +++++++++++++++--- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/lodash.src.js b/lodash.src.js index 5aba9004b..7ad5b758d 100644 --- a/lodash.src.js +++ b/lodash.src.js @@ -2581,7 +2581,7 @@ if (isLength(srcValue.length) && (isArray(srcValue) || isTypedArray(srcValue))) { result = isArray(value) ? value - : (value ? arrayCopy(value) : []); + : ((value && value.length) ? arrayCopy(value) : []); } else if (isPlainObject(srcValue) || isArguments(srcValue)) { result = isArguments(value) diff --git a/test/test.js b/test/test.js index 3cbea52a8..848205a8c 100644 --- a/test/test.js +++ b/test/test.js @@ -9995,8 +9995,10 @@ }); test('should work with four arguments', 1, function() { - var expected = { 'a': 4 }; - deepEqual(_.merge({ 'a': 1 }, { 'a': 2 }, { 'a': 3 }, expected), expected); + var expected = { 'a': 4 }, + actual = _.merge({ 'a': 1 }, { 'a': 2 }, { 'a': 3 }, expected); + + deepEqual(actual, expected); }); test('should assign `null` values', 1, function() { @@ -10009,7 +10011,7 @@ deepEqual(actual, { 'a': 1 }); }); - test('should not not error on DOM elements', 1, function() { + test('should not error on DOM elements', 1, function() { var object1 = { 'el': document && document.createElement('div') }, object2 = { 'el': document && document.createElement('div') }, pairs = [[{}, object1], [object1, object2]], @@ -10038,6 +10040,16 @@ deepEqual(actual, expected); }); + test('should convert values to an array when merging with arrays of `source`', 2, function() { + var object = { 'a': { '1': 'y', 'b': 'z', 'length': 2 } }, + actual = _.merge(object, { 'a': ['x'] }); + + deepEqual(actual, { 'a': ['x', 'y'] }); + + actual = _.merge({ 'a': {} }, { 'a': [] }); + deepEqual(actual, { 'a': [] }); + }); + test('should work with a function `object` value', 2, function() { function Foo() {}