Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix nested objects being modified #15

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ function mixin(target, val, key) {
let obj = target[key];
if (isObject(val) && isObject(obj)) {
mixinDeep(obj, val);
} else if (!(key in target) && isObject(val)) {
// `target` can be mutated by later mixins. Therefore, if we are currently adding an object to `target`,
// it could be mutated later. We need to make sure that mutation will not change the original data.
target[key] = {...val};
} else {
target[key] = val;
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "mixin-deep",
"description": "Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone. No dependencies.",
"version": "2.0.1",
"version": "3.0.0",
"homepage": "https://github.com/jonschlinkert/mixin-deep",
"author": "Jon Schlinkert (https://github.com/jonschlinkert)",
"repository": "jonschlinkert/mixin-deep",
Expand Down
15 changes: 14 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,19 @@ describe('.mixinDeep()', function() {
assert.notDeepEqual(actual, obj3);
});

it('should copy properties onto the first object without modifying other sub-objects', function() {
const obj1 = { x: { a: 0, b: 1 } };
const obj2 = { x: { c: 2, d: 3 } };
const obj3 = { x: { a: 4, d: 5 } };

const actual = { x: { a: 4, b: 1, c: 2, d: 5 } };

assert.deepEqual(mixinDeep({}, obj1, obj2, obj3), actual);
assert.notDeepEqual(actual, obj1);
assert.notDeepEqual(actual, obj2);
assert.notDeepEqual(actual, obj3);
});

it('should mixin nested object properties', function() {
const obj1 = { a: { b: 1, c: 1, d: { e: 1, f: 1 } } };
const obj2 = { a: { b: 2, d: { f: 'f' } } };
Expand Down Expand Up @@ -79,7 +92,7 @@ describe('.mixinDeep()', function() {

const actual = mixinDeep({}, obj1, obj2);
assert.deepEqual(actual, { a: { b: 1, c: 2 } });
assert.deepEqual(actual.a, obj1.a);
assert.notDeepEqual(actual.a, obj1.a);
assert.notDeepEqual(actual.a, obj2.a);
});

Expand Down