Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally push an item in an observable array?

Tags:

knockout.js

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.

like image 476
jaffa Avatar asked Dec 07 '11 14:12

jaffa


Video Answer


1 Answers

An observableArray exposes an indexOf function (wrapper to ko.utils.arrayIndexOf). This allows you to do:

if (myObservableArray.indexOf(itemToAdd) < 0) {   myObservableArray.push(itemToAdd); } 

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:

var match = ko.utils.arrayFirst(myObservableArray(), function(item) {     return itemToAdd.id === item.id; });  if (!match) {   myObservableArray.push(itemToAdd); } 
like image 61
RP Niemeyer Avatar answered Sep 20 '22 15:09

RP Niemeyer