Javascript:过滤对象数组

时间:2017-08-24 14:24:42

标签: javascript arrays filter

我在这里做错了什么?



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'}

3 个答案:

答案 0 :(得分:4)

filter()函数不是 mutable - 这意味着它会返回带有过滤对象的 new 数组并执行'变异'原始数组 - 您必须将其分配给另一个变量 - 请参阅下面的演示:



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

employee = { location_id: 1 }

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

console.log(result);




答案 1 :(得分: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);

答案 2 :(得分:1)

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

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

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