How to append to a mapped observable array in knockout.js?

by dalton_moen , in category: Javascript , a month ago

How to append to a mapped observable array in knockout.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by mallory_cormier , a month ago

@dalton_moen 

To append to a mapped observable array in knockout.js, you can directly push the new item to the original array and then update the mapped array by calling the refresh method. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
var data = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' }
];

var observableArray = ko.observableArray(data);

var mappedItems = ko.pureComputed(function() {
  return ko.utils.arrayMap(observableArray(), function(item) {
    return { id: item.id, name: item.name };
  });
});

// Append a new item to the original array
observableArray.push({ id: 3, name: 'Charlie' });

// Update the mapped array
mappedItems.refresh();


By calling refresh on the mapped array after appending the new item to the original array, the UI will be updated to reflect the new data.


Alternatively, you can also append to the mapped array directly by pushing the new item, like this:

1
mappedItems.push({ id: 3, name: 'Charlie' });


This will update the UI automatically since the mapped array is also an observable array.