pt0
pt0

Reputation: 175

parse multidimensional json object in jQuery

Here is the object:

{
    "358":  { "order_name": "NAME3", "parts": [
            { "part_name": "item1", "part_state": "add" },
            { "part_name": "item2", "part_state": "add" },
            { "part_name": "item3", "part_state": "remove" }
        ]
    },
    "359":  { "order_name": "NAME4"}
};

Here is my attempt, I cannot get the part_name nor part_state by repeating the $.each function.

$.each( orders, function ( i, order ) {
    console.log( "ORDER ID: " + i + "->" + order.order_name );

    $.each( order, function ( j, part ) {
        console.log( part );
    });
});

Upvotes: 0

Views: 57

Answers (1)

A. Wolff
A. Wolff

Reputation: 74420

part is an array of object(s). What you can use is:

$.each(orders, function (i, order) {
    console.log("ORDER ID: " + i + "->" + order.order_name);
    if (!order.parts) return;
    $.each(order.parts, function (j, part) {
        console.log(part.part_name, part.part_state);    
    });
});

Upvotes: 3

Related Questions