首页 > 解决方案 > 从对象获取属性以转换为简单数组 - javascript

问题描述

我有这个数组:

[
  {
    "id": "5e235b42a21b160a40c4a82f",
    "title": "category one"
  },
  {
    "id": "5e235b3ea21b160a40c4a82e",
    "title": "category two"
  }
]

我想将其转换为以下数组:

[
  "5e235b42a21b160a40c4a82f",
  "5e235b3ea21b160a40c4a82e"
]

有人有一个简单的建议吗?

标签: javascriptarrays

解决方案


The best way to do this is by iterating over the Object values and taking each id value.

The simplest way of doing this is by using .map() like so:

const newArray = myArray.map(item => item.id);

This should take each item and form the id property into an array.


推荐阅读