【问题标题】:How does one filter array items by an item's nested property value如何通过项的嵌套属性值过滤数组项
【发布时间】:2020-09-10 16:04:22
【问题描述】:

我有一个数据项列表,每个数据项包含来自同一属性的许多不同嵌套属性值之一,例如 AB,例如employeeType。我需要创建一个只包含 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"
  }
}];
            

预期输出

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

我试过这个,但得到一个错误 filter of undefined

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

【问题讨论】:

  • element.subElements 应该是什么?您的对象中没有 subElements 属性。
  • 在这里努力遵循您的逻辑。你有一个对象数组,而不是一个对象。如果要创建数组的深层副本,为什么不直接过滤并映射数组?如果您真的只想要一次迭代,请使用 reduce?
  • 由于您没有更改任何列表项的结构,因此不需要map,从您的预期结果来看,您显然想要filter
  • 如果subElements 是包含字符串employee 的变量,请参见stackoverflow.com/questions/4244896/…
  • 应该是 employees 我错过了在问题中更改它

标签: javascript arrays filter


【解决方案1】:

您只需使用过滤器即可实现这一目标

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

【讨论】:

    【解决方案2】:

    这应该够了吧?

    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)

    【讨论】:

    • 如果箭头函数的主体只是一个return 语句,你应该使用简写形式。
    • 我想说:“可以”使用简写形式。 “应该”太强了。
    • “应该”可能有点强,但我明白你的意思。我发现有些人,特别是新程序员,所有的速记都会有点混乱。所以我通常把整个括号放在一起,特别是如果他们想编辑代码,就不容易出错了。
    猜你喜欢
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 2018-01-16
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多