Skip to content

Commit 4bef120

Browse files
committed
fix: preserve source when removing nested values
1 parent c241125 commit 4bef120

2 files changed

Lines changed: 9 additions & 8 deletions

File tree

‎src/utils/set.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,10 @@ function internalSet<Entity = any, Output = Entity, Value = any>(
2525

2626
// Delete prop if `removeIfUndefined` and value is undefined
2727
if (removeIfUndefined && value === undefined && restPath.length === 1) {
28-
delete clone[path][restPath[0]];
28+
const origin = clone[path];
29+
const child = Array.isArray(origin) ? [...origin] : { ...origin };
30+
delete child[restPath[0]];
31+
clone[path] = child;
2932
} else {
3033
clone[path] = internalSet(clone[path], restPath, value, removeIfUndefined);
3134
}

‎tests/utils.test.ts‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -59,14 +59,12 @@ describe('utils', () => {
5959
expect(set({}, ['notExist'], undefined, true)).toEqual({});
6060

6161
// Delete value
62-
const target = set(
63-
{ keep: { light: 2333 } },
64-
['keep', 'light'],
65-
undefined,
66-
true,
67-
);
68-
expect(target).toEqual({ keep: {} });
62+
const source = { keep: { light: 2333, bamboo: 1 } };
63+
const target = set(source, ['keep', 'light'], undefined, true);
64+
expect(target).toEqual({ keep: { bamboo: 1 } });
6965
expect('light' in target.keep).toBeFalsy();
66+
expect(source).toEqual({ keep: { light: 2333, bamboo: 1 } });
67+
expect(target.keep).not.toBe(source.keep);
7068

7169
// Mid path not exist
7270
const midTgt = set(

0 commit comments

Comments
 (0)