Skip to content

Instantly share code, notes, and snippets.

@searene
Last active December 5, 2017 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save searene/05578c5e6fa8cf5559174d560d4611ea to your computer and use it in GitHub Desktop.
Save searene/05578c5e6fa8cf5559174d560d4611ea to your computer and use it in GitHub Desktop.
Show posts recursively
function printComments(comments, depth) {
for(var i = 0; i < comments.length; i++) {
var c = comments[i];
console.log(getSpaces(depth * 2) + "My post is " + c.post);
if(c.hasOwnProperty("children")) {
printComments(c.children, depth + 1);
}
}
}
function getSpaces(n_spaces) {
spaces = "";
for(var i = 0; i < n_spaces; i++) {
spaces += " ";
}
return spaces;
}
json = [
{
id: 2,
post: 73,
parent: 0,
children: [
{
id: 3,
post: 73,
parent: 2
}
],
},
{
id: 4,
post: 29,
parent: 0
}
];
printComments(json, 0);
/* Output:
My post is 73
My post is 73
My post is 29
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment