I am trying to learn recursion in Javascript, so I figured I\'d rewrite the native JSON.stringify function using recursion as a challenge to myself. I almost got my
I was asked this in an Interview question and this is what I came up with. An understandable recursive approach:
function stringify(input) {
var arrVals = [];
Object.keys(input).forEach(function(keyName) {
let val = input[keyName];
if (typeof val !== 'undefined' && typeof val !== 'function') {
arrVals.push(getQuotedString(keyName) + ":" + getString(val));
}
});
return '{' + arrVals.join(',') + '}';
}
function getString(val) {
switch (typeof val) {
case 'string':
return getQuotedString(val);
break;
case 'number':
case 'boolean':
return val;
break;
case 'object':
if (val === null) {
return "null";
}
if (Array.isArray(val)) {
let arrString = []
for (let i = 0; i < val.length; i++) {
arrString.push(getString(val[i]));
}
return "[" + arrString.join(',') + "]";
}
return stringify(val);
break;
}
}
function getQuotedString(str) {
return '"' + str + '"';
}
Test using following obj:
var input = {
"a": 1,
"b": 'text',
"c": {
"x": 1,
"y": {
"x": 2
}
},
"d": false,
"e": null,
"f": undefined,
"g": [1, "text", {
a: 1,
b: 2
}, null]
};