2017-10-11 89 views
1

我需要過濾基於另一個數組中可變數量項目的數組。 說要過濾我的數組像這個樣子:動態構建表達式來過濾Javascript數組

var toBeFiltered = [ 
    {name:"A", parentId: 0}, 
    {name: "B", parentId: 3}, 
    {name: "C", parentId: 0}, 
    {name: "D", parentId: 1}, 
    ... 
] 

我需要過濾所有這parentId是另一個數組中的元素(比如:var filtering = [3,1,0],但它可以爲任意長度)。 如何根據filtering數組的內容動態地創建過濾器表達式?在這種情況下,我最終得到這個表達式:

function(d){return d.parentId == 3 || d.parentId == 1 || d.parentId == 0;} 

有沒有什麼聰明的方法可以做到這一點?像布爾表達式的串聯?

回答

4

您可以使用indexOf方法檢查給定的array中是否存在item

indexOf如果未找到value,則會返回指定值的第一個匹配項並返回-1

var toBeFiltered = [ 
 
    {name:"A", parentId: 0}, 
 
    {name: "B", parentId: 3}, 
 
    {name: "C", parentId: 0}, 
 
    {name: "D", parentId: 1}, 
 
    {name: "E", parentId: 4} 
 
] 
 
var filtering = [3,1,0]; 
 
toBeFiltered=toBeFiltered.filter(a=>filtering.indexOf(a.parentId)!==-1); 
 
console.log(toBeFiltered);

您也可以使用來自ES6Set功能。

var toBeFiltered = [ 
 
    {name:"A", parentId: 0}, 
 
    {name: "B", parentId: 3}, 
 
    {name: "C", parentId: 0}, 
 
    {name: "D", parentId: 1}, 
 
    {name: "E", parentId: 4} 
 
] 
 
var filtering = new Set([3,1,0]); 
 
toBeFiltered=toBeFiltered.filter(a=>filtering.has(a.parentId)); 
 
console.log(toBeFiltered);

+1

古樸典雅。我沒有想過這個。謝謝。 – GuitarExtended

+0

@GuitarExtended,不客氣。 –

2

你可以採取Array#includes

var toBeFiltered = [{ name:"A", parentId: 0 }, { name: "B", parentId: 3 }, { name: "C", parentId: 0 }, { name: "D", parentId: 1 }], 
 
    filtering = [1, 0], // to prevent to get the same array as the original 
 
    result = toBeFiltered.filter(o => filtering.includes(o.parentId)); 
 
    
 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

+0

謝謝。我接受了其他答案,因爲include比indexOf支持的更少。 – GuitarExtended