2014-02-24 266 views
0

我想檢查對象數組中是否存在某個值。在數組對象中查找元素

舉例來說,如果我有這樣的事情:

[ { _id: 1,  
    name: foo }, 
    { _id: 2,  
    name: bar }, 
    { _id: 3,  
    name: foox }, 
    { _id: 4,  
    name: fooz }, 
    ] 


var search = [1,25,33,4,22,44,5555,63] 

然後我要檢查,如果在search的一個值是包含的對象的數組中的對象之一。

+0

此外,你在檢查搜索陣列你反對? ID? – Andy

+0

是的,我不知道我是否必須循環搜索或對象...我嘗試http://sugarjs.com/api/Array/find – Twinsen

回答

1
var list = [ { _id: 1, name: "foo" }, 
    { _id: 2, name: "bar" }, 
    { _id: 3, name: "foox" }, 
    { _id: 4, name: "fooz" }, 
]; 


var search = [1,25,33,4,22,44,5555,63]; 

list.forEach(function(element){ 
    if(search.indexOf(element._id) != -1){ 
     console.log("found"); 
    } 
}); 

試試這個,希望這是你在找什麼。

0

如果:

var o = [{ _id: 1, name: "foo"}, { _id: 2, name: "bar"}, { _id: 3, name: "foox"}, { _id: 4, name: "fooz"}]; 
var search = [1, 25, 33, 4, 22, 44, 5555, 63]; 

試試這個:

var outPus = o.filter(function(u){ 
    return search.some(function(t){ return t == u._id}) 
}) 

或本:

var outPut = []; 
search.forEach(function(u){ 

    o.forEach(function(t){ 

     if(t._id == u) outPut.push(t) 
    }) 
}) 
0
var list = [ { _id: 1,  
    name: foo }, 
    { _id: 2,  
    name: bar }, 
    { _id: 3,  
    name: foox }, 
    { _id: 4,  
    name: fooz }, 
    ]; 

var isAnyOfIdsInArrayOfObject = function(arrayOfObjects, ids){ 
    return arrayOfObjects.some(function(el) { return ids.indexOf(el._id) !== -1; }); 
} 
1

這將返回ID的列表,然後如果至少鍛鍊搜索陣列中的一個元素位於該列表中:

var found = arr.map(function (el) { 
    return el._id; 
}).some(function (el) { 
    return search.indexOf(el) > -1; 
}); 

Fiddle

some很有趣,因爲它在找到第一個匹配時立即跳出檢查。

0
var list = [ 
    { _id: 1, name: 'foo' }, 
    { _id: 2, name: 'bar' }, 
    { _id: 3, name: 'foox' }, 
    { _id: 4, name: 'fooz' } 
]; 

var search = [1,25,33,4,22,44,5555,63]; 

此代碼建立在search這也是你list所有元素的列表:

var inArr = search.filter(function(index){ 
    return list.some(function(el){ 
    return el._id === index; 
    }); 
}); 
console.log(inArr); // [1,4]; 

很明顯,你可以切換listsearch身邊讓你獲得與元素的數組listsearch

var elements = list.filter(function(el){ 
    return search.some(function(index){ 
    return el._id === index; 
    }); 
}); 
console.log(elements); // [{ _id: 1, name: 'foo' },{ _id: 4, name: 'fooz' }]