简体   繁体   中英

How does one filter array items by an item's nested property value

I have a list of data items each containing one of many different nested property values like A or B from the same property like eg employeeType . I need to create a new array that only contains objects thats value for employee.employeeType equals "B" .

const data = [{
  "id": 80,
  "employee": {
    "employeeType":"A"
  }
}, {
  "id": 250,
  "employee": {
    "employeeType" :"B"
  }
}, {
  "id": 263,
  "employee": {
    "employeeType" :"A"
  }
}, {
  "id": 267,
  "employee": {
    "employeeType" :"A"
  }
}, {
  "id": 272,
  "employee": {
    "employeeType" :"A"
  }
}, {
  "id": 281,
  "employee": {
    "employeeType" :"B"
  }
}];
            

Expected ouput

[{
  "id": 250,
  "employee": {
    "employeeType" :"B"
  }
}, {
  "id": 281,
  "employee": {
    "employeeType" :"B"
  }
}]

I tried this but get an error of filter of undefined

const updatedData = data.map((element) => {
    return {...element, subElements: element.subElements.filter((subElement) => 
    subElement.employeeType === "B")}
 })

您可以仅使用过滤器来实现

data.filter(item => item.employee.employeeType === "B")

This should be enough?

const results = data.filter(item =>  {
   return item.employee.employeeType === 'B'
 })

 const data = [ { "id": 80, "employee": { "employeeType":"A" } }, { "id": 250, "employee": { "employeeType" :"B" } }, { "id": 263, "employee": { "employeeType" :"A" } }, { "id": 267, "employee": { "employeeType" :"A" } }, { "id": 272, "employee": { "employeeType" :"A" } }, { "id": 281, "employee": { "employeeType" :"B" } } ] const results = data.filter(item => { return item.employee.employeeType === 'B' }) console.log(results)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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