-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
68 lines (54 loc) · 1.79 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* Iterates through the whole json and replaces searchValue with newValue
* Works on simple string, json, array
* @param {JSON/Array/String} input
* @param {String} searchValue
* @param {String} newValue
*/
const jnestedReplace = (input, searchValue, newValue, skipKeys=[]) => {
// Validate for input, searchValue and newValue
// throws error if any value is undefined/null
if (!input || !searchValue || !newValue) {
throw new Error('JSON, searchValue, newValue cannot be null');
}
// If input is not json
if (!isObject(input) && !isArray(input)) {
throw new Error('Invalid JSON');
}
// Iterate over the object and find and replace values
for (let key in input) {
// If type is object, call the same function recursively
if (isObject(input[key])) {
input[key] = jnestedReplace(input[key], searchValue, newValue, skipKeys);
continue;
}
// If type is array, call the same function recursively
// for every element of array
if (isArray(input[key])) {
for (let i=0; i<input[key].length; i++) {
input[key][i] = jnestedReplace(input, searchValue, newValue, skipKeys);
}
continue;
}
// If the key needs to be skipped.
// Do not process and continue to next element
if (skipKeys.indexOf(key) === -1 && isString(input[key])) {
input[key] = input[key].replace(searchValue, newValue);
}
}
return input;
};
// Checks if data is an object
const isObject = (data) => {
return data instanceof Object;
};
// checks if data is an array
const isArray = (data) => {
return data instanceof Array;
};
// check id the data is string
const isString = (data) => {
return typeof data === 'string'
&& Object.prototype.toString.call(data) === '[object String]';
};
module.exports = jnestedReplace;