Q:

Need to add depth class according to parent id

I need to add depth class according to parent_id. 
Json Data :
[
{"id":1,"name":"one","parent_id":0},
{"id":2,"name":"two","parent_id":0},
{"id":3,"name":"three","parent_id":0},
{"id":4,"name":"four","parent_id":0},
{"id":5,"name":"five","parent_id":0},
{"id":6,"name":"one","parent_id":2},
{"id":7,"name":"two","parent_id":6},
{"id":8,"name":"three","parent_id":6},
{"id":9,"name":"four","parent_id":8},
{"id":10,"name":"five","parent_id":8},
]

Result Should be :
<ul class="menu">
    <li class="depth-0 menu-item-1"><li>
    <li class="depth-0 menu-item-2"><li>
    <li class="depth-1 menu-item-6"><li>
    <li class="depth-2 menu-item-8"><li>
    <li class="depth-3 menu-item-9"><li>
    <li class="depth-3 menu-item-10"><li>
    <li class="depth-2 menu-item-7"><li>
    <li class="depth-0 menu-item-3"><li>
    <li class="depth-0 menu-item-4"><li>
    <li class="depth-0 menu-item-5"><li>
</ul>

i have tried 
$.each(data, function(i, item) {
    if(item.parent_id > 0){
        $(this).addClass('depth-1');
    }
});

if item parent_id is 0 then class should be depth-0 if item has parent_id (child item) then class should be depth-1 and if has (sub child item) depth-2.  any one can guide me how can do this ? 

A:

Try this way:
var depths = [];

$.each(data, function(i, item) {
    depths[item.id] = (depths[item.parent_id] || 0) + 1;
});

This would give you an array with depths (starting from 1)
So for the data
var data = [
{"id":1,"name":"one","parent_id":0},
{"id":2,"name":"two","parent_id":0},
{"id":3,"name":"three","parent_id":0},
{"id":4,"name":"four","parent_id":0},
{"id":5,"name":"five","parent_id":0},
{"id":6,"name":"one","parent_id":2},
{"id":7,"name":"two","parent_id":6},
{"id":8,"name":"three","parent_id":6},
{"id":9,"name":"four","parent_id":8},
{"id":10,"name":"five","parent_id":8},
];

So depths array would be: 
[undefined, 1, 1, 1, 1, 1, 2, 3, 3, 4, 4]

ie menu item 1 has depth of 1, menu item 6 has depth of 2... similar to your example. 
Now iterate over the depths array & generate the menu items...

