diff --git a/index.js b/index.js index c5dc494..2cc37b9 100644 --- a/index.js +++ b/index.js @@ -44,6 +44,18 @@ function extend(target, obj) { target[key] = val; } target[key] = assign(target[key] || {}, val); + } else if (isArray(val)) { + var array = []; + for (var i = 0; i < val.length; i++) { + if (isPrimitive(val[i])) { + array.push(val[i]); + } else { + array.push(assign({}, val[i])); + } + + } + target[key] = array; + } else { target[key] = val; } @@ -60,6 +72,13 @@ function isObject(obj) { return typeOf(obj) === 'object' || typeOf(obj) === 'function'; } +/** + * Returns true if the object is an array. + */ +function isArray(obj) { + return typeOf(obj) === 'array'; +} + /** * Returns true if the given `key` is an own property of `obj`. */ diff --git a/test.js b/test.js index 9f6a72c..a10b44a 100644 --- a/test.js +++ b/test.js @@ -130,7 +130,7 @@ describe('assign', function() { var two = {e: 'f', g: ['h']}; assign(one, two); assert.deepEqual(one.g, ['h']); - assert.equal(one.g, two.g); + assert.deepEqual(one.g, two.g); assert.equal(typeof one, 'function'); }); @@ -322,5 +322,28 @@ describe('symbols', function() { var res = assign(a, b); assert.equal(res[key], 'xyz'); }); + + it('should deeply assign properties in an array:', function() { + var template = { + b: [ + { + + a: { + a: 0 + } + } + ] + }; + var one = assign({}, template); + var two = assign({}, template); + one.b[0].a = { + b: 0 + }; + two.b[0].a = { + c: 0 + }; + + assert.deepEqual(one.b[0].a, {b: 0}); + }); } });