使用数组映射以 if 条件过滤结果 [英] Using array map to filter results with if conditional

查看:29
本文介绍了使用数组映射以 if 条件过滤结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用数组映射进一步过滤对象,以准备将其发送到服务器进行保存.我可以过滤到 1 个键值,这很好,但我想更进一步,并根据内部的布尔值检查它们.

I am trying to use an array map to filter a object a bit further to prepare it to send to the server to for saving. I can filter to 1 key value, which is great, but I want to take it 1 step further and check them against a boolean inside.

所以,现在这就是我所拥有的 -

So, right now this is what I have -

$scope.appIds = $scope.applicationsHere.map( function(obj){
        if(obj.selected == true){
            return obj.id;
        }
    });

这对于提取 id 非常有用,但是如果它们的选定值 == false,我不想将它们推送到这个新数组中,所以我放置了一个条件来进一步过滤.这有点有效,我得到了一个 id 数组,但是具有 .selected == false 的 id 仍然在数组中,只是值为 null.所以如果我在对象中有 4 个项目,其中 2 个是假的,它看起来像这样 -

This works great for pulling out the id's, however I don't want to push them in this new array if they their selected value == false, so I put a conditional to filter further. This somewhat works, I get an array of id's, but the id's that have .selected == false are still in the array, just with the value of null. So If I have 4 items in the object and 2 of them are false it looks like this -

 appIds = {id1, id2, null, null};

我的问题是 - 有没有办法做到这一点,而无需将空值放入其中.感谢阅读!

My question is - is there a way to do this without the nulls being put in there. Thanks for reading!

推荐答案

您正在寻找 .filter() 函数:

  $scope.appIds = $scope.applicationsHere.filter(function(obj) {
    return obj.selected;
  });

这将生成一个数组,其中仅包含selected"属性为 true(或真值)的那些对象.

That'll produce an array that contains only those objects whose "selected" property is true (or truthy).

edit 抱歉,我正在喝咖啡,但我错过了评论 - 是的,正如 jAndy 在评论中指出的那样,过滤然后只提取id"值,它会是:

edit sorry I was getting some coffee and I missed the comments - yes, as jAndy noted in a comment, to filter and then pluck out just the "id" values, it'd be:

  $scope.appIds = $scope.applicationsHere.filter(function(obj) {
    return obj.selected;
  }).map(function(obj) { return obj.id; });

一些函数式库(比如 Functional,在我看来它没有得到足够的爱)有一个 .pluck() 函数从对象列表中提取属性值,但原生 JavaScript 有一组非常精简的此类工具.

Some functional libraries (like Functional, which in my opinion doesn't get enough love) have a .pluck() function to extract property values from a list of objects, but native JavaScript has a pretty lean set of such tools.

这篇关于使用数组映射以 if 条件过滤结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆