-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
49 lines (39 loc) · 1.08 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
'use strict';
function deepSet(obj, property, value) {
const visited = new Map();
return iterate(obj, property, value, visited)
}
function iterate(obj, property, value, visited) {
if (obj == null) {
return obj;
}
if (visited.get(obj) != null) {
return visited.get(obj);
}
const result = {};
Object.keys(obj).forEach( key => result[key] = obj[key] );
if (property in result) {
result[property] = value;
}
visited.set(obj, result);
iterateNested(result, property, value, visited);
return result;
}
function iterateNested(obj, property, value, visited) {
const objKeys = Object.keys(obj).filter(k => k != property)
objKeys.forEach( key => {
const current = obj[key];
if (typeof current === 'object') {
obj[key] = iterate(current, property, value, visited);
}
if (Array.isArray(current)) {
obj[key] = current.map(otherObj => {
if (typeof otherObj === 'object') {
return iterate(otherObj, property, value, visited);
}
return otherObj;
});
}
});
}
module.exports.deepSet = deepSet