根据条件打破React JS中的map()函数

Tan*_*ria 1 javascript arrays list higher-order-functions reactjs

要求:基本上我在 React JS 中有一个员工对象数组,比如 empList。这个 empList 包含原始字段和另一个“地址”对象的内部数组,例如 addressList。我想获取属于城市“ABC”的所有员工的数据。它们在城市“ABC”中可以有多个地址,但它们应该只被提取一次并被推入 FinalList 一次。

问题:我能够过滤在城市“ABC”中有地址的员工,但如果他们在城市“ABC”有多个地址,那么他们会被多次添加到最终列表中。因此,我想检查一名员工的所有地址,以防万一在城市“ABC”中找到任何地址,我想将其添加到 FinalList,打破这个内部 map() 函数并转到外部 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.
Run Code Online (Sandbox Code Playgroud)

use*_*994 5

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

阅读some 此处

var finalList =  empList.filter(e => e.addressList.some(a => a.city.startsWith("ABC")));
Run Code Online (Sandbox Code Playgroud)

另外,我还更新了您的逻辑以使用filter(而不是map)创建一个新数组,其中包含通过所提供条件的所有元素。

您可以filter此处阅读相关内容。