Anthony
Anthony

Reputation: 1581

Adding to an array javascript

I have created the array var aData = []; and I want to add to the array using a web service. I've used the following code which retrieves the last item:

var GSUserAfterFindRecord = function (sender) {
    UserVM.ModelList = ko.observableArray(UserVM.Model.GetDataList());
    var list = {};

    $.each(UserVM.Model.GetDataList(), function (index, item) {
        list = { name: item.Name };
    });
    aData.push(list);
    oModel.refresh();
}

But I want to retrieve all items not just the last. Instead of list = { name: item.Name }; I've tried list += { name: item.Name } but that returns a blank table. I've used console.log to see what is being pushed to aData and when adding the + I get: ["[object Object][object Object][object Object][obje…ect][object Object][object Object][object Object]"] without the + I get [Object].

I should mention that I am using a sapui5 table that is why I have oModel.refresh but I think this can be done without knowing the fact that I am using a sapui5 table.

Upvotes: 0

Views: 2554

Answers (2)

Jite
Jite

Reputation: 5847

If you make the list object into an array (it is currently a object) and then move the push part into the each loop, you will be able to add each item to the array.
The Array.prototype.push method adds one item to the array.

var list = [];
$.each(UserVM.Model.GetDataList(), function (index, item) {
    list.push({ name: item.Name });
});

Or just use the aData array in the each loop instead of creating a new temporary array!

Upvotes: 5

Appsincaps
Appsincaps

Reputation: 36

Try this:

list[name] = item.Name; instead of list = { name: item.Name };

Upvotes: 0

Related Questions