【问题标题】:Filtering for Multiple Fields in Object Array in Javascript/Lodash在 Javascript/Lodash 中过滤对象数组中的多个字段
【发布时间】:2017-02-23 11:05:30
【问题描述】:

我有以下数组:

人员列表

[ {id:1, name:"Brian", status:"active"}, {id:2, name:"Mary", status:"active"},
  {id:3, name:"John", status:"pending"}, {id:4, name:"Steph", status:"pending"},
 {id:5, name:"Peter", status:"inactive"}
]

状态列表

[ 'active', 'pending']

我想将对象数组过滤为仅 statusList,所以我做了以下操作:

var filteredPeople  =PeopleList.map(person => {
  for (var i=0; i<=statusList.length; i++){
    if(statusList[i] == person.active)
        return {...person};
  }
});

虽然人员对象正确返回,但对于未通过条件语句的对象,我也会得到“未定义”。

所以我的结果是:

   [object, object, object,object, undefined ] 

我怎样才能做到,如果条件不通过,我从列表中删除该对象?

【问题讨论】:

    标签: javascript arrays object lodash


    【解决方案1】:

    您应该使用filter 而不是map 来过滤数组。你也可以使用includes

    var data = [ {id:1, name:"Brian", status:"active"}, {id:2, name:"Mary", status:"active"},
      {id:3, name:"John", status:"pending"}, {id:4, name:"Steph", status:"pending"},
     {id:5, name:"Peter", status:"inactive"}
    ]
    var statusList = [ 'active', 'pending']
    
    var result = data.filter(e => statusList.includes(e.status))
    console.log(result)

    对于 ES5 和更早的版本,您可以使用 indexOf 而不是 includes

    var data = [ {id:1, name:"Brian", status:"active"}, {id:2, name:"Mary", status:"active"},
      {id:3, name:"John", status:"pending"}, {id:4, name:"Steph", status:"pending"},
     {id:5, name:"Peter", status:"inactive"}
    ]
    var statusList = [ 'active', 'pending']
    
    var result = data.filter(function(e) {
      return statusList.indexOf(e.status) != -1
    })
    console.log(result)

    【讨论】:

      【解决方案2】:
      var statusList = [];
      
      var PeopleList = [
      
        { id: 1, name: "Brian", status: "active" },
        { id: 2, name: "Mary", status: "active" },
        { id: 3, name: "John", status: "pending" },
        { id: 4, name: "Steph", status: "pending" },
        { id: 5, name: "Peter", status: "inactive" }
      
      ];
      
      for (var counter = 0; counter < PeopleList.length; counter++)
      {
      
      statusList.push(PeopleList[counter].status);
      
      document.write(PeopleList[counter].status + "<br />");
      }
      
      // Here is your Status array
      console.log(statusList);
      
      // loop through all elements in your javascript status array and print them out
      for (var i = 0; i < statusList.length; i++)
      {
      
          document.write("<strong>" + statusList[i] + "<br />");
      }
      

      【讨论】:

        猜你喜欢
        • 2019-05-13
        • 2017-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-17
        • 2018-08-22
        相关资源
        最近更新 更多