I would like to push
a new item onto an observableArray
, but only if the item is not already present. Is there any "find" function or recommended pattern for achieving this in KnockoutJS?
I've noticed that the remove
function on an observableArray
can receive a function for passing in a condition. I almost want the same functionality, but to only push it if the condition passed in is or is not true.
Thanks RP. Here's an example of using your suggestion to return the 'name' property via the object's 'id' property from within my view model.
In HTML, i have the following ($parent is due to this being inside a table row loop):
An observableArray exposes an
indexOf
function (wrapper toko.utils.arrayIndexOf
). This allows you to do:If the two are not actually a reference to the same object and you want to run custom comparison logic, then you can use
ko.utils.arrayFirst
like:search a object in a ko.observableArray
http://jsfiddle.net/rathore_gee/Y4wcJ/
I would add "valueWillMutate()" before changes and "valueHasMutated()" after them.