【发布时间】:2020-10-06 20:52:47
【问题描述】:
我正在尝试展平一个数组,但在这方面遇到了一些问题。我有这些数据可供展平。
arr = [
{
"data": [
[
{
"_id": "5ee97ee7f25d1c1482717bdf",
"email": "test1@test.io",
"profileImages": [],
"username": "test1",
"birthday": "2020-06-11T10:11:32.000Z",
"phoneNumber": "+910000000000",
"location": "Test Location",
"firstName": "test1",
"lastName": "test1",
}
],
[
{
"_id": "5ee97ef2f25d1c1482717be1",
"email": "test2@test.io",
"profileImages": [],
"username": "test2",
"birthday": "2020-06-11T10:11:32.000Z",
"phoneNumber": "+910000000000",
"location": "Test Location"
}
]
]
}
],
这就是我所拥有的......并且我希望这些数据以某种方式将数据合并到一个数组中,如下面的结构
data: [
{
"_id": "5ee97ee7f25d1c1482717bdf",
"email": "test1@test.io",
"profileImages": [],
"username": "test1",
"birthday": "2020-06-11T10:11:32.000Z",
"phoneNumber": "+910000000000",
"location": "Test Location",
"firstName": "test1",
"lastName": "test1"},
{
"_id": "5ee97ef2f25d1c1482717be1",
"email": "test2@test.io",
"profileImages": [],
"username": "test2",
"birthday": "2020-06-11T10:11:32.000Z",
"phoneNumber": "+910000000000",
"location": "Test Location"
}
]
我曾尝试使用 lodash 库将其展平,但没有成功。对此有何建议,我如何将这些数组展平为单个数组?
【问题讨论】:
-
arr.flatMap(k=>k.data.flat()) -
flatMap和flat()并未在所有浏览器中得到广泛支持。所以最安全的选择是使用简单的递归。看看下面的答案
标签: javascript arrays mongodb flatten