112233
112233

Reputation: 2466

How to call array element by name or index within loop?

This is the script:

for(var i=0;i < data.length; i++)
{
    new_array.push(data[i].catalog_name,data[i].price);
    $("#print_receipt").append(
        "<table><thead><tr><th>Item Name</th><th>Unit Price</th></thead><tbody>");

    for (var j=0;j < new_array.length; j++){
        $.each(new_array[j], function( index, value ) {
            $("#print_receipt tbody").append("<tr><td>"+value+"</td></tr>");
        });                         
    }
    $("#print_receipt").append(value+"</tbody></table>");
}

"+value+" This line actually outputs all the values of both arrays that were pushed into new_array by this line new_array.push(data[i].catalog_name,data[i].price);

That is okay, but I want to be able to call them individually. For instance, in the event I want make a table within this $.each loop, how do I know, which columns takes which array's value?

So, how do I call, value.catalog_name or value.price within $.each instead of just value?

Upvotes: 0

Views: 65

Answers (1)

Richard Theobald
Richard Theobald

Reputation: 777

The problem is that you are doing things using arrays, and javascript arrays are numeric index only. Instead, make new_array into an object containing objects, and then you are able to retrieve things by name.

var new_array = {};
for(var i=0;i < data.length; i++)
{
    new_array[i] = ({ 'catalog_name':data[i].catalog_name, 'price':data[i].price });
}
$("#print_receipt").append( "<table><thead><tr><th>Item Name</th><th>Unit Price</th></thead><tbody>");
$.each(new_array, function() {
    $("#print_receipt tbody").append("<tr><td>"+this.catalog_name+"</td><td>"+this.price+"</td></tr>");
});
$("#print_receipt").append("</tbody></table>");

https://jsfiddle.net/8weoun7c/

Upvotes: 1

Related Questions