I have two arrays (contacts & contactsSelected) both with the following type of structure:
{
id: 1,
name: bob
},
{
id: 213,
name: Rob
}
I'm using KnockoutJS. How Can I iterate over contacts() and for each row, determine if that row's ID is contained in the contactsSelected array? In KnockoutJS I have something like this:
userCardModel.contactsToShow = ko.dependentObservable(function () {
return ko.utils.arrayFilter(this.contacts(), function(contact) {
return /////////////// LOGIC GOES HERE TO See if this contact.id() is contained开发者_如何学编程 in the contactsSelected() array
});
}, userCardModel);
Thanks
OK, you could do it like so...
var contactsSelectedLength = contacts.length;
for (var i = 0, contactsLength = contacts.length; i++) {
var contact = contacts[i];
for (var j = 0; j < contactsSelectedLength; j++) {
var selectedContact = contactsSelected[j];
if (contact.id == selectedContact.id) {
// It is in there!
}
}
}
Add the IDs of "contactsSelected" as properties of an object so they can be accessed in better-than-linear time using the "in" operator or "hasOwnProperty" method:
var getSelectedIds = function(sel) {
var len=sel.length, o={}, i;
for (i=0; i<len; i++) {
o[sel[i].id] = true;
}
return o;
};
var selectedIds = getSelectedIds(contactsSelected);
(1 in selectedIds); // => true
(2 in selectedIds); // => false
selectedIds.hasOwnProperty(213); // => true
selectedIds.hasOwnProperty(214); // => false
精彩评论