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"}]
asked Nov 12, 2019 at 22:42
user3580480
4827 gold badges16 silver badges48 bronze badges
2 Answers 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);
answered Nov 12, 2019 at 22:45
Emanuele Scarabattoli
4,4601 gold badge14 silver badges26 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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.
answered Nov 12, 2019 at 23:21
A1rPun
17k8 gold badges60 silver badges93 bronze badges
Comments
lang-js
{ }does not create an array; it creates an object.ids.map()