使用数组映射来筛选结果,如果有条件 [英] Using array map to filter results with if conditional

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

问题描述

我正在尝试使用数组映射来过滤一个对象,进一步准备它发送到服务器进行保存。我可以过滤到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,但是我不想把它们推入这个新的数组如果他们选择的值为==,那么我把一个条件进一步过滤。这有点工作,我得到一个id的数组,但id的.selected == false仍然在数组中,只是值为null。所以如果我在对象中有4个项目,其中2个是false,它看起来像这样 -

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

我的问题是 - 有没有一个方法可以做到这一点,没有nulls被放在那里。感谢您阅读!

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

推荐答案

您正在寻找 .filter() function:

You're looking for the .filter() function:

  $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).

编辑对不起,我在喝点咖啡,是的,正如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.

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

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