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 code to work:
var my_stringify = function(obj){
value = obj[ Object.keys(obj)[0] ];
index = Object.keys(obj)[0];
delete obj[ Object.keys(obj)[0] ];
// The value is just a simple string, not a nested object
if (typeof value === 'string'){
if (Object.keys(obj).length !== 0){
// Continue recursion ..
return '"' + index + '":"' + value + '",' + my_stringify(obj);
}
// This would be the base case with a string at the end. Stop recursion.
return '"' + index + '":"' + value + '"}';
}
// The value is actually a nested object
else{
if (Object.keys(obj).length !== 0){
// Continue recursion ..
return '"' + index + '":{' + my_stringify(value) + ',' + my_stringify(obj);
}
// This is the base case with a nested object at the end. Stringify it and end recursion.
return '"' + index + '":{' + my_stringify(value) + '}';
}
}
Except for the fact that the first {
in my answer is missing, and I can't figure out how to fix this bug.
E.g. my_stringify({foo: 'bar'})
returns "foo":"bar"}
instead of {"foo":"bar"}
.
Also, I'm aware I'm completely destroying the original object, is there any way to send over to recursion a reduced version of the original object without deleting anything (something like obj.slice(1)
)?
Any advice will be greatly appreciated !
See Question&Answers more detail:os