Skip to content

Commit 44767ce

Browse files
committed
Enhance setIn tool
1 parent 0a7daf0 commit 44767ce

File tree

2 files changed

+51
-2
lines changed

2 files changed

+51
-2
lines changed

src/set-in.test.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,42 @@ const testCases: {
7575
}
7676
]
7777
}
78+
},
79+
{
80+
parameters: [
81+
{
82+
key1: [
83+
{
84+
key3: 'prev value'
85+
}
86+
]
87+
},
88+
'key1[0].key3',
89+
'new value'
90+
],
91+
result: {
92+
key1: [
93+
{
94+
key3: 'new value'
95+
}
96+
]
97+
}
98+
},
99+
{
100+
parameters: [
101+
{
102+
key1: [null]
103+
},
104+
'key1[0].key3',
105+
'new value'
106+
],
107+
result: {
108+
key1: [
109+
{
110+
key3: 'new value'
111+
}
112+
]
113+
}
78114
}
79115
];
80116

src/set-in.ts

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,24 @@ const setInRecursive = (
3434
} else if (isPlainObject(current)) {
3535
current[key] = value;
3636
} else {
37+
console.log(current);
3738
throw new Error('Last chain must be an object or array');
3839
}
3940
} else {
40-
if (isPlainObject(current)) {
41-
if (!current.hasOwnProperty(key)) {
41+
if (sampleIsArray) {
42+
if (numberKey) {
43+
if (!(Array.isArray(current[key]) || isPlainObject(current[key]))) {
44+
current[key] = typeof path[nextIndex] === 'number' ? [] : {};
45+
}
46+
setInRecursive(current[key], value, path, nextIndex);
47+
} else {
48+
throw new Error(`Key \`${key}\` must be an array index (correct int)`);
49+
}
50+
} else if (isPlainObject(current)) {
51+
if (
52+
!current.hasOwnProperty(key) ||
53+
!(Array.isArray(current[key]) || isPlainObject(current[key]))
54+
) {
4255
// setting inner prop based on next path index
4356
current[key] = typeof path[nextIndex] === 'number' ? [] : {};
4457
}

0 commit comments

Comments
 (0)