【问题标题】:Correct way to filter out a specific key from an array of objects? [duplicate]从对象数组中过滤掉特定键的正确方法? [复制]
【发布时间】:2022-01-18 16:02:40
【问题描述】:

我有这个对象数组...

[
  {
    "id": 1,
    "application": "Default Case Set",
    "errorSource": "CASEWORK",
    "message": 34,
    "stackTrace": 0,
    "date": 0,
    "user": 0
  },
  {
    "id": 2,
    "application": "Default",
    "errorSource": "CASEWORK",
    "message": 39,
    "stackTrace": 2,
    "date": 0,
    "user": 0
   }
]

我想创建一个如下所示的 id 数组...

[1, 2]

最好的方法是什么?

谢谢!

【问题讨论】:

  • 你在哪里卡住了?你最好的尝试是什么?

标签: javascript arrays filter


【解决方案1】:

使用Array.map 从每个对象中提取id 属性值。

const arr = [
  {
    "id": 1,
    "application": "Default Case Set",
    "errorSource": "CASEWORK",
    "message": 34,
    "stackTrace": 0,
    "date": 0,
    "user": 0
  },
  {
    "id": 2,
    "application": "Default",
    "errorSource": "CASEWORK",
    "message": 39,
    "stackTrace": 2,
    "date": 0,
    "user": 0
   }
]

const result = arr.map(e => e.id)
console.log(result)

【讨论】:

  • 谢谢!成功了!
猜你喜欢
  • 2017-11-10
  • 2022-11-17
  • 1970-01-01
  • 2017-09-06
  • 1970-01-01
  • 1970-01-01
  • 2020-02-13
  • 1970-01-01
  • 2018-09-28
相关资源
最近更新 更多