Last active
October 2, 2015 21:18
-
-
Save JeffJacobson/2323547 to your computer and use it in GitHub Desktop.
Convert object to HTML list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Writes the properties of an object to a definition list. | |
* @param Any type of object. | |
* @return {string} Returns a definition list for most objects. Returns an ordered list for Arrays. Strings and Dates will return a string. | |
*/ | |
function objectToList(obj) { | |
var name, output, t, v; | |
t = typeof(obj); | |
if (t === "undefined") { | |
output = ""; | |
} else if (obj === null){ | |
output = "null"; | |
} else if (t === "object") { | |
if (obj instanceof Array) { | |
output = ["<ol>"]; | |
(function(){ | |
var i, l; | |
for (i = 0, l = obj.length; i < l; i += 1) { | |
output.push(["<li>", objectToList(obj[i]), "<li>"].join()); | |
} | |
}()); | |
output.push("</ol>"); | |
output = output.join(""); | |
} else if (obj instanceof Date) { | |
output = String(obj); | |
} else { | |
// Initialize the output list. | |
// output = $("<dl>"); | |
output = ["<dl>"]; | |
// Loop through all of the properties of the object and add them to the list. | |
for (name in obj) { | |
if (obj.hasOwnProperty(name)) { | |
// $("<dt>").text(name).appendTo(output); | |
output.push(["<dt>", name, "</dt>"].join("")); | |
// Get the value of the property and its type. | |
v = obj[name]; | |
t = typeof(v); | |
// $("<dd>").append(objectToList(v)).appendTo(output); | |
output.push(["<dd>", objectToList(v), "</dd>"].join("")); | |
} | |
} | |
output.push("</dl>"); | |
output = output.join(""); | |
} | |
} else { | |
output = obj; | |
} | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment