Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse json array in jquery in foreach loop

I'm trying to parse json array with objects and use them to create multiple checkboxes. This is what I have:

JSON data:

[{
    "ID": 1,
    "Name": "Bacon",
    "Description": "",
    "Price": 0
}, {
    "ID": 2,
    "Name": "Beef",
    "Description": "",
    "Price": 0
}, {
    "ID": 3,
    "Name": "Chicken",
    "Description": "",
    "Price": 0
}, {
    "ID": 4,
    "Name": "Ham",
    "Description": "",
    "Price": 0
}]

In the JS code I have this:

success: function (data) {
    var objects = JSON.stringify(data);
    for (var key in objects) {
        var checkBox = "<input type='checkbox' data-price='" + key.Price + "' name='" + key.Name + "' value='" + key.ID + "'/>" + key.Name + "<br/>";
        $(checkBox).appendTo('#modifiersDiv');
    };
    $('#addModifiers').modal('show');
}

But the key object doesn't contain any data. My question is how I can do foreach loop and get the data I need and fetch that data in the checkbox properties.

like image 907
Laziale Avatar asked Feb 06 '26 01:02

Laziale


1 Answers

Your data should already be a javascript array because you've specified the JSON type for the jQuery Ajax call so it should have already parsed the JSON into javascript. As such, you can just directly iterate it as the array:

success: function (data) {
    for (var i = 0; i < data.length; i++) {
        var checkBox = "<input type='checkbox' data-price='" + data[i].Price + "' name='" + data[i].Name + "' value='" + data[i].ID + "'/>" + data[i].Name + "<br/>";
        $(checkBox).appendTo('#modifiersDiv');
    }
    $('#addModifiers').modal('show');
}

Or, if you want to use jQuery's .each() iterator instead of a for loop, you can do this:

success: function (data) {
    $.each(data, function(key, item) {
        var checkBox = "<input type='checkbox' data-price='" + item.Price + "' name='" + item.Name + "' value='" + item.ID + "'/>" + item.Name + "<br/>";
        $(checkBox).appendTo('#modifiersDiv');
    });
    $('#addModifiers').modal('show');
}
like image 189
jfriend00 Avatar answered Feb 07 '26 13:02

jfriend00