2

I am trying to create an array in javascript.

Here is my code:

        var arr = {};

        for (q = 0; q < ids.length; q++) {
            var rowId = ids[q];
            var rowData = jQuery("#<%= JQGrid2.ClientID %>").jqGrid('getRowData', rowId);

            arr["section"] = rowData.inv_section;
            arr["po"] = rowData.cust_po;
            arr["description"] = rowData.description;   

        };

        console.log(arr);

The result of the above code is:

{description: "Telephone Calls", po: "PO3547", section: "Telephony"}

However I would like to concatenate all the items in the loop, so I end up with an array, that looks like the below:

[{description: "Telephone Calls", po: "PO3547", section: "Telephony"},
{section: Telephony, po: "PO0067", description: "ISDN"}, 
{section: Managed Service, po: "PO0066", description: "Desktop Support"}, 
{section: Managed Service, po: "PO0066", description: "Desktop Support"}]
user3580480
  • 442
  • 7
  • 14
  • 45

2 Answers2

2

You are initializing your "array" as an object. Change your code in the following way:

var arr = [];

for (q = 0; q < ids.length; q++) {
    var rowId = ids[q];
    var rowData = jQuery("#<%= JQGrid2.ClientID %>").jqGrid('getRowData', rowId);

    var item = {}

    item["section"] = rowData.inv_section;
    item["po"] = rowData.cust_po;
    item["description"] = rowData.description;   

    arr.push(item)
};

console.log(arr);
Emanuele Scarabattoli
  • 4,103
  • 1
  • 12
  • 21
2

You are essentially mapping a list of id's to a list of corresponding objects. Try the following functional approach to minimize initialization errors.

const arr = ids.map(rowId => {
  const rowData = jQuery("#<%= JQGrid2.ClientID %>").jqGrid('getRowData', rowId);

  return {
    section: rowData.inv_section,
    po: rowData.cust_po,
    description: rowData.description,
  };
});

console.log(arr);

Edit: After my post I see the comment of @Barmar.

A1rPun
  • 16,287
  • 7
  • 57
  • 90