简体   繁体   English

如何使用 array.map 函数不返回任何内容(空数组)

[英]how to return nothing ( empty array) with array.map function

Right now, if 'Everything' in the list is detected, the output becomes [""].现在,如果检测到列表中的“所有内容”,则输出变为 [""]。
Expected output: []预期输出:[]

Copy.names = rule.names.map(function(x) {                                
    if (x.name ==='Everything') {                                   
        return '';
    } else {
        return x.name;
    }
});

Use Array.prototype.filter:使用 Array.prototype.filter:

Copy.names = rule.names.filter(function(x) {                                
    return x.name !=='Everything';
}).map(function (x) {
    return x.name;
});

Another solution with Array.filter(): Array.filter() 的另一个解决方案:

names.map(
  (x) => x.name === 'Everything' && x.name
).filter(Boolean)

If you can use ES6, you can use generator for that:如果你可以使用 ES6,你可以使用生成器:

Copy.names = Array.from(function* () {
    for (var x of rule.names) {
       if (x.name ==='Everything') {                                   
            // do nothing
       } else {
            yield x.name;
       }
    }
})

If not... you can always go for imperative way:如果没有......你总是可以采取命令式的方式:

Copy.names = []

for (var x of rule.names) {
   if (x.name ==='Everything') {                                   
        // do nothing
   } else {
        Copy.names.push(x.name);
   }
}

If you can use Lodash (which I highly recommend), you can deal with it in elegant way by using _.flatMap :如果您可以使用 Lodash(我强烈推荐),您可以使用_.flatMap以优雅的方式处理它:

Copy.names = _.flatMap(rule.names, function(x) {
    if (x.name ==='Everything') {                                   
        return [];
    } else {
        return [x.name];
    }
})

As you can see, it's similiar to map , except that you return array of items instead of item.如您所见,它与map类似,不同之处在于您返回的是项目数组而不是项目。

An answer I wrote elsewhere covers this, but if you want to be able to accomplish the transform of Array.map() but also to change the output length, you would need to use Array.reduce() .我在其他地方写的一个答案涵盖了这一点,但是如果您希望能够完成Array.map()的转换,还希望更改输出长度,则需要使用Array.reduce()

Usually, though, it will make more sense to filter--preferably before you map, but if needed, then after.但是,通常,过滤会更有意义——最好在映射之前,但如果需要,然后在之后。

For this you should use reduce instead of map, here an example:为此,您应该使用 reduce 而不是 map,这里是一个示例:

Copy.names = rule.names.reduce(function (arr, x) {
  x.name !== 'Everything' && arr.push(x.name)
  return arr
}, [])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM