@@ -215,23 +215,48 @@ const DynamicJsonForm = ({
215
215
return ;
216
216
}
217
217
218
- const newValue = {
219
- ...( typeof value === "object" && value !== null && ! Array . isArray ( value )
220
- ? value
221
- : { } ) ,
222
- } as JsonObject ;
223
- let current : JsonObject = newValue ;
218
+ const updateArray = ( array : JsonValue [ ] , path : string [ ] , value : JsonValue ) : JsonValue [ ] => {
219
+ const [ index , ...restPath ] = path ;
220
+ const arrayIndex = Number ( index ) ;
221
+ const newArray = [ ...array ] ;
222
+
223
+ if ( restPath . length === 0 ) {
224
+ newArray [ arrayIndex ] = value ;
225
+ } else {
226
+ newArray [ arrayIndex ] = updateValue ( newArray [ arrayIndex ] , restPath , value ) ;
227
+ }
228
+ return newArray ;
229
+ } ;
224
230
225
- for ( let i = 0 ; i < path . length - 1 ; i ++ ) {
226
- const key = path [ i ] ;
227
- if ( ! ( key in current ) ) {
228
- current [ key ] = { } ;
231
+ const updateObject = ( obj : JsonObject , path : string [ ] , value : JsonValue ) : JsonObject => {
232
+ const [ key , ...restPath ] = path ;
233
+ const newObj = { ...obj } ;
234
+
235
+ if ( restPath . length === 0 ) {
236
+ newObj [ key ] = value ;
237
+ } else {
238
+ newObj [ key ] = updateValue ( newObj [ key ] , restPath , value ) ;
229
239
}
230
- current = current [ key ] as JsonObject ;
231
- }
240
+ return newObj ;
241
+ } ;
242
+
243
+ const updateValue = ( current : JsonValue , path : string [ ] , value : JsonValue ) : JsonValue => {
244
+ if ( path . length === 0 ) return value ;
245
+
246
+ if ( ! current ) {
247
+ current = ! isNaN ( Number ( path [ 0 ] ) ) ? [ ] : { } ;
248
+ }
249
+
250
+ if ( Array . isArray ( current ) ) {
251
+ return updateArray ( current , path , value ) ;
252
+ } else if ( typeof current === 'object' && current !== null ) {
253
+ return updateObject ( current , path , value ) ;
254
+ }
255
+
256
+ return current ;
257
+ } ;
232
258
233
- current [ path [ path . length - 1 ] ] = fieldValue ;
234
- onChange ( newValue ) ;
259
+ onChange ( updateValue ( value , path , fieldValue ) ) ;
235
260
} ;
236
261
237
262
return (
0 commit comments