首页 > 解决方案 > Filter a JSON array based on a property

问题描述

I have a JSON array like this:

var records = [
  { Name: "Bob", EmployeeID: 1234, Status: "present" },
  { Name: "Jim", EmployeeID: 4432, Status: "present" },
  { Name: "Heather", EmployeeID: 4432, Status: "absent" },
]

And I want to filter the array list according to the status like(i.e if Status === "present").

[
  { "Name": "Bob", "EmployeeID": 1234, "Status": "present" },
  { "Name": "Jim", "EmployeeID": 4432, "Status": "present" }
]

标签: javascriptarrays

解决方案


使用Array#filter仅获取present状态记录。

该方法使用通过所提供函数实现的测试的所有元素filter()创建一个新元素。array

var records = [{
    "Name": "Bob",
    "EmployeeID": 1234,
    "Status": "present"
  },
  {
    "Name": "Jim",
    "EmployeeID": 4432,
    "Status": "present"
  },
  {
    "Name": "Heather",
    "EmployeeID": 4432,
    "Status": "absent"
  }
];

let preStatus = records.filter(({Status}) => Status === 'present')
console.log(preStatus)


推荐阅读