Skip to content

Commit fda3986

Browse files
Add "deep-update" example.
1 parent 405287d commit fda3986

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Diff for: temp/deep-update.js

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*! European Union Public License version 1.2 !*/
2+
/*! Copyright © 2020 Rick Beerendonk !*/
3+
4+
// Immutable deep update.
5+
6+
function update(obj, keyArray, value) {
7+
if (keyArray.length === 0) {
8+
return value;
9+
}
10+
11+
const first = keyArray.shift();
12+
return {
13+
...obj,
14+
[first]: update(obj[first], keyArray, value)
15+
};
16+
}
17+
18+
const obj1 = {
19+
data: 0,
20+
level1: {
21+
data: 1,
22+
level2: {
23+
data: 2,
24+
level3: {
25+
data: 3
26+
}
27+
}
28+
}
29+
};
30+
31+
const obj2 = update(obj1, 'level1.level2.data'.split('.'), 99);
32+
33+
console.log(JSON.stringify(obj1));
34+
console.log(JSON.stringify(obj2));

0 commit comments

Comments
 (0)