简体   繁体   中英

Create array in Javascript, with Keys

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"}]

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM