Let's say I am dealing with JSON like this:
http://hndroidapi.appspot.com/nestedcomments/format/json/id/4620423?appid=hntoolbar&callback=
Which can be infinitely nested. I want to extract all of the comment information in a "flattened" format, just a list of usernames and the contents of their comment without worrying about the "level" of the comment. How would I do something like that using Javascript/JQuery?
use recursion:
var getall = function(comments,out) {
var out = out || {};
var cuser = undefined;
var comment;
for (var key in comments) {
if (key == 'username') {
cuser = comments[key];
continue;
}
if (key == 'comment') {
comment = comments[key];
continue;
}
var mytype = typeof(comments[key]);
if (mytype == 'object'
|| mytype == 'array') {
out=getall(comments[key],out);
};
}
if (cuser !== undefined) {
if (out[cuser] === undefined) {
out[cuser] = [];
}
out[cuser].push(comment);
}
return (out);
}
b=getall(a);
console.log(b);
a here - parsed JSON, b - result;
b structure is
{user1: [comment,comment,comment],user2: [] ...}
http://jsfiddle.net/NkTst/1/
check http://jsfiddle.net/NkTst/2/ if you still need extended info on comments
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With