Reputation:
I have a project that requires me to convert an Object to a string, without using stringify. The aim of this is to implement a recursive function that converts an object to a string. I seem to be having 2 problems here:
1) My function to output the Object as a string, only seems to be outputting the first value, not the rest.
function myToString(argObj) {
var str = "";
for (var val in argObj) {
if (argObj.hasOwnProperty(val)) {
str += val + " : " + argObj[val] + "\n";
console.log(str);
}
return str;
}
}
2) My understanding of the above for in loop, would be that it would print each key/value pair in the object, but it is only doing so for the first key/value. Using recursion, how can I get this to run over each key/value pair.
Upvotes: 0
Views: 311
Reputation: 23945
You had your return value inside the for loop, meaning it returned on the first iteration through it. Try this:
function myToString(argObj) {
var str = "";
for (var val in argObj) {
if (argObj.hasOwnProperty(val)) {
str += val + " : " + argObj[val] + "\n";
document.write(str);
}
}
return str;
}
After that you want to know if any of the properties of argObj are objects so you can recursively call the function on any of them. From this SO post grab a function to test if a variable is an object. You probably do not want to include arrays in your recursive call. You probably want to print their contents. (but that is another question hey) Then your code becomes something like this:
function myAndSomeGuyOnStackOverflowToString(argObj) {
var str = "";
for (var val in argObj) {
if (argObj.hasOwnProperty(val)) {
var propertyValue = argObj[val];
if (isAnObject(propertyValue)){
propertyValue = myAndSomeGuyOnStackOverflowToString(propertyValue)
}
str += val + " : " + propertyValue + "\n";
document.write(str);
}
}
return str;
}
function isAnObject(objArg){
//choose your implementation from the many on that other post I mentioned
}
And with some indentation and string formatting you should be well on your way.
Upvotes: 2
Reputation: 1251
function myToString(argObj, res) {
if ( argObj !== null && typeof argObj === "object") {
for (var val in argObj)
res += val + " : " + argObj[val] + "\n";
}
if (typeof argObj === "number" || typeof argObj === "string")
return res + argObj;
return res;
}
Invoke this function by calling myToString(object, "")
, it returns a string. Hope it can help you or give you some idea to write it recursively.
Upvotes: 0