I got tired of having to do this over and over. So here's a little thing I
wrote just for fun. Recursive depth-first preorder traversal for objects
and arrays. I hacked this out pretty quickly from some real code, so you
might^H^H^H^H^H will find bugs. Not sure how deep the JS stack but I think
this function can be rewritten with a helper to emulate tail recursion
elimination. So please don't blame me if it takes your server down!
walker(news,''); // second param is empty string
// NOT FOR PRODUCTION
function walker(x,indent) {
Object.keys(x).forEach(function(key) {
var value = x[key];
console.log('k:'+indent + key);
if ('object' == typeof(value)) {
walker(value, indent + ' ');
} else {
console.log('v:'+indent + ' ' + x[key]);
}
});
};
var news = [
{ "section": "sports",
"reports":
[
{"story": "New Coach", "text": "Lorem"},
{"scores": "soccer"},
{"scores": "rugby"}
]
},
{ "section": "world",
"stories":
[
{"headline": "Madrid Protesters", "text": "Ispum"}
]
},
{ "section": "real eastate",
"listings":
[
{"property": "Greek Condo Fire Sale", "price": "OBO"},
{"property": "Malibu Beachhouse", "price": "add more
zeros"}
]
}
];
On Thu, Mar 22, 2012 at 3:58 AM, Angelo Chen <[email protected]>wrote:
> Hi,
>
> sorry if this is not node related:
>
> var areas = [{"news":"1"}, {"story":"1"}]
> console.log(areas)
>
> areas.forEach(function (e, i) {
> console.log(i)
> console.log(e)
> })
>
>
> how to get key and value in the forEach? Thanks,
>
> Angelo
>
> --
> Job Board: http://jobs.nodejs.org/
> Posting guidelines:
> https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
> You received this message because you are subscribed to the Google
> Groups "nodejs" group.
> To post to this group, send email to [email protected]
> To unsubscribe from this group, send email to
> [email protected]
> For more options, visit this group at
> http://groups.google.com/group/nodejs?hl=en?hl=en
>
--
Job Board: http://jobs.nodejs.org/
Posting guidelines:
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en