JS to Text Converter
by Shobhit Sharma
JavaScript
function convertToText(obj) {
var string = [];
if (obj === 'undefined') {
return JSON.stringify(undefined);
}
if (!obj) {
return JSON.stringify(obj || Boolean(obj));
}
if (typeof(obj) == "object" && (obj.join == undefined)) {
string.push("{");
for (prop in obj) {
string.push(prop, ": ", convertToText(obj[prop]), ",");
};
string.push("}");
//is array
} else if (typeof(obj) == "object" && !(obj.join == undefined)) {
string.push("[")
for (prop in obj) {
string.push(convertToText(obj[prop]), ",");
}
string.push("]")
//is function
} else if (typeof(obj) == "function") {
string.push(obj.toString())
//all other values can be done with JSON.stringify
} else {
string.push(JSON.stringify(obj))
}
return string.join("")
}
var objDeep = {
'my-string': {
func: function(e) {
console.log(e);
},
mix: [
function(e) {
console.log('array', e);
},
1,
2,
'coco',
{
poop: true,
deep: [
true,
{
pooping: {
ok: true
},
cow: [
'goat', true, null, undefined
]
}
]
}
]
},
str: 'potato',
num: 100
};
console.log(convertToText(objDeep))