Javascript:过滤数组对象

问题描述:

我在这里做错了什么?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'。所以,如果你明白了,你一定在做着非常不同的事情。 –

filter()功能不可变 - 这意味着它返回一个阵列与过滤对象,做“变异”原来阵列 - 你必须将其分配给另一个变量 - 看看下面的演示:

​​

您需要为滤波的结果与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);

您需要存储的.filter()结果。它不会改变原始数组。


在附注中,您可以通过删除大括号和返回语句来缩短回调函数。

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