的JavaScript。检查Object是否包含对象

时间:2014-07-06 12:26:19

标签: javascript

我有两个对象数组

//references
var refs=[
         {id:1,   name:'John',    state:'A'},
         {id:2,   name:'Obama',   state:'P'},
         {id:3,   name:'Lincoln', state:'P'}
];

//items
var items=[
          {ref:refs[0],    detailed:true },
          {ref:refs[1],    detailed:false}
];

现在我想检查项目是否包含 refs [0] 。我该怎么做?我们当然可以做到 像这样的东西

for(item:items){
 if(item.ref==refs[0]){
  console.log('contains');
  break;
 }
}

但我可能有2000个参考。有任何想法吗。谢谢

2 个答案:

答案 0 :(得分:2)

您可以使用Array.filter()

console.log(get_ref_item(refs[0], items));

function get_ref_item(ref, items) {
    return items.filter(function fi(item){
        return ref.id == item.ref.id;
    });
}

http://jsfiddle.net/5MfrT/

答案 1 :(得分:0)

不清楚这里的问题是什么,但假设您想知道参考是否在物品中并且您需要知道多个参考(多次查找),那么您最好重新定义您的物品:

//references
var refs=[
         {id:1,   name:'John',    state:'A'},
         {id:2,   name:'Obama',   state:'P'},
         {id:3,   name:'Lincoln', state:'P'}
];

//items
var items=[
          {ref:refs[0],    detailed:true },
          {ref:refs[1],    detailed:false}
];

//if you need to continiously look up a ref in items
// it's better to convert items to an object
// {"refid":{ref:..,detailed:...}}
// assuming every item has a ref and has that ref only once
// and every ref has a unique id
var i = -1,len=items.length,tmp={};
while(++i<len){
  tmp[items[i].ref.id]=items[i];
}
items=tmp;

console.log("item for refs 0:",items[refs[0].id]);
console.log("item for refs 1:",items[refs[1].id]);
console.log("item for refs 2:",items[refs[2].id]);//undefined, that ref is not it items