Skip to content

Instantly share code, notes, and snippets.

@JeffJacobson
Last active October 2, 2015 21:18
Show Gist options
  • Save JeffJacobson/2323547 to your computer and use it in GitHub Desktop.
Save JeffJacobson/2323547 to your computer and use it in GitHub Desktop.
Convert object to HTML list
/**
* 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