-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstringifyNumbers.js
46 lines (41 loc) · 970 Bytes
/
stringifyNumbers.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
/////////// Recursion Coding Exercise 22: stringifyNumbers ///////////////////
// Write a function called stringifyNumbers which takes in an object and finds all of the values which
// are numbers and converts them to strings. Recursion would be a great way to solve this! Do not change original obj.
let obj = {
num: 1,
test: [],
data: {
val: 4,
info: {
isRight: true,
random: 66,
},
},
};
function stringifyNumbers(obj) {
let newObj = Array.isArray(obj) ? [] : {};
for (let key in obj) {
if (Number.isInteger(obj[key])) {
newObj[key] = obj[key].toString();
} else if (obj[key] === Object(obj[key])) {
newObj[key] = stringifyNumbers(obj[key]);
} else {
newObj[key] = obj[key];
}
}
return newObj;
}
console.log(stringifyNumbers(obj));
/*
{
num: "1",
test: [],
data: {
val: "4",
info: {
isRight: true,
random: "66"
}
}
}
*/