2017-08-24 154 views
-2

我在這裏做錯了什麼?Javascript:過濾數組對象

var locations = [ 
 
     { id: 1, name: 'N'}, 
 
     { id: 2, name: 'P'} 
 
    ] 
 

 
var employee = { location_id: 1 } 
 

 
locations.filter((location) => { 
 
    return location.id == employee.location_id 
 
}); 
 

 
console.log(locations);

這個返回undefined當我試圖使它返回{ id: 1, name: 'N'}

+5

此代碼適用於我。 –

+0

它實際上返回一個包含該對象的數組。嘗試使用'Array.prototype.findIndex'來獲取數組中對象的索引。 – lukaleli

+0

這段代碼當然不會以任何方式產生'undefined'。所以,如果你明白了,你一定在做着非常不同的事情。 –

回答

4

filter()功能不可變 - 這意味着它返回一個陣列與過濾對象,做「變異」原來陣列 - 你必須將其分配給另一個變量 - 看看下面的演示:

​​

1

您需要爲濾波的結果與Array#filter

filter()方法創建與通過由提供的功能實現的測試中所有元素的數組變量。

var locations = [ 
 
     { id: 1, name: 'N'}, 
 
     { id: 2, name: 'P'} 
 
    ], 
 
    employee = { location_id: 1 }, 
 
    result = locations.filter((location) => { 
 
     return location.id == employee.location_id 
 
    }); 
 

 
console.log(result);

1

您需要存儲的.filter()結果。它不會改變原始數組。


在附註中,您可以通過刪除大括號和返回語句來縮短回調函數。

locations = locations.filter(loc => loc.id == employee.location_id);