|
5 | 5 | * @param {String} searchValue |
6 | 6 | * @param {String} newValue |
7 | 7 | */ |
8 | | -const jnestedReplace = (input, searchValue, newValue) => { |
| 8 | +const jnestedReplace = (input, searchValue, newValue, skipKeys=[]) => { |
9 | 9 |
|
10 | 10 | // Validate for input, searchValue and newValue |
11 | 11 | // throws error if any value is undefined/null |
12 | 12 | if (!input || !searchValue || !newValue) { |
13 | | - throw 'JSON, searchValue, newValue cannot be null'; |
| 13 | + throw new Error('JSON, searchValue, newValue cannot be null'); |
| 14 | + } |
| 15 | + |
| 16 | + // If input is not json |
| 17 | + if (!isObject(input) && !isArray(input)) { |
| 18 | + throw new Error('Invalid JSON'); |
14 | 19 | } |
15 | 20 |
|
16 | 21 | // Iterate over the object and find and replace values |
17 | 22 | for (let key in input) { |
18 | 23 |
|
19 | 24 | // If type is object, call the same function recursively |
20 | | - if (typeof input[key] === 'object') { |
21 | | - input[key] = jnestedReplace(input[key], searchValue, newValue); |
| 25 | + if (isObject(input[key])) { |
| 26 | + input[key] = jnestedReplace(input[key], searchValue, newValue, skipKeys); |
22 | 27 | continue; |
23 | 28 | } |
24 | 29 |
|
25 | 30 | // If type is array, call the same function recursively |
26 | 31 | // for every element of array |
27 | | - if (typeof input[key] === 'array') { |
| 32 | + if (isArray(input[key])) { |
28 | 33 | for (let i=0; i<input[key].length; i++) { |
29 | | - input[key][i] = jnestedReplace(input, searchValue, newValue); |
| 34 | + input[key][i] = jnestedReplace(input, searchValue, newValue, skipKeys); |
30 | 35 | } |
31 | 36 | continue; |
32 | 37 | } |
33 | 38 |
|
34 | | - // Find and replace the value |
35 | | - input[key] = input[key].replace(searchValue, newValue); |
| 39 | + // If the key needs to be skipped. |
| 40 | + // Do not process and continue to next element |
| 41 | + if (skipKeys.indexOf(key) === -1) { |
| 42 | + input[key] = input[key].replace(searchValue, newValue); |
| 43 | + } |
36 | 44 | } |
37 | 45 |
|
38 | 46 | return input; |
39 | | -} |
| 47 | +}; |
| 48 | + |
| 49 | + |
| 50 | +// Checks if data is an object |
| 51 | +const isObject = (data) => { |
| 52 | + return data instanceof Object; |
| 53 | +}; |
| 54 | + |
| 55 | +// checks if data is an array |
| 56 | +const isArray = (data) => { |
| 57 | + return data instanceof Array; |
| 58 | +}; |
40 | 59 |
|
41 | 60 |
|
42 | 61 | module.exports = jnestedReplace; |
0 commit comments