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"}]
4
  • 3
    { } does not create an array; it creates an object. Commented Nov 12, 2019 at 22:43
  • You need to create a new object each time through the loop, and then push it onto the array. Commented Nov 12, 2019 at 22:43
  • 1
    Also consider using ids.map() Commented Nov 12, 2019 at 22:44
  • Possible duplicate of How to add an object to an array Commented Nov 12, 2019 at 22:49

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.