鉴于两个阵列 - contacts()& contactsSelected() - 如何匹配这两个?

时间:2011-04-19 01:00:20

标签: javascript json knockout.js

我有两个阵列(contacts& contactsSelected),它们都具有以下类型的结构:

{
    id: 1,
    name: bob
},
{
    id: 213,
    name: Rob
}

我正在使用KnockoutJS。我如何迭代contacts()和每行,确定该行的ID是否包含在contactsSelected数组中?在KnockoutJS中,我有类似的东西:

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);

由于

2 个答案:

答案 0 :(得分:2)

好的,你可以这样做......

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!
       }
   }
}

答案 1 :(得分:1)

将“contactsSelected”的ID添加为对象的属性,以便使用“in”运算符或“hasOwnProperty”方法以比线性更好的时间访问它们:

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