React JS中的Break map()函数基于条件



需求:基本上我有一个数组的员工对象在React JS,说empList。该示例列表包含基本字段&同样是另一个"地址"的内部数组对象,说addressList。我想获取所有员工的数据,如果他们属于城市"ABC"。他们可以有多个地址在城市"ABC",但他们应该只取一次">

问题:我能够过滤地址在城市"ABC"但如果他们在城市"ABC"中有多个地址,那么他们将被多次添加到最终列表中。因此,我想检查员工的所有地址&如果在城市"ABC"中找到任何一个,我想将其添加到finalList,打破这个内部map()函数&到outer map()查看下一个员工

下面是我的代码片段

var finalList =[];
empList.map(function(employee) {

var valid = employee.addressList.map(function(address) {
if (address.city.startsWith("ABC")) {
finalList.push(employee);
//Employee pushed to validList once, so now break from inner map() function & goto second line/execute on next employee object 

}
});     //.slice(0,1); Slice doesn't work here since I want the condition to be true first, then break it.

可以使用some来测试数组中是否至少有一个元素通过测试条件。

在这里阅读some

var finalList =  empList.filter(e => e.addressList.some(a => a.city.startsWith("ABC")));

我也更新了你的逻辑使用filter(而不是map),它创建了一个新的数组,所有元素通过提供的条件。

你可以在这里阅读filter

最新更新