我有下面的例子数组(对象):
[
{
"id": 1,
"name": "selling",
"detail": [
{
"id": 11,
"name": "sale-report",
"detail": [
{ "id": 111, "name": "sale-report1", "detail": [] },
{ "id": 112, "name": "sale-report2", "detail": [] }
]
}
]
},
{
"id": 2,
"name": "webstore",
"detail": [
{
"id": 11,
"name": "sale-report",
"detail": [
{ "id": 111, "name": "webstore-report1", "detail": [] },
{ "id": 112, "name": "webstore-report2", "detail": [] }
]
}
]
},
{
"id": 2,
"name": "setting",
"detail": [
{
"id": 11,
"name": "general",
"detail": [
{ "id": 111, "name": "setting-general1", "detail": [] },
{ "id": 112, "name": "setting-general2", "detail": [] }
]
}
]
}
]
如何将数组更改为新格式,如下所示
[
{
"id": 1,
"name": "selling",
},
{
"id": 11,
"name": "sale-report"
},
{ "id": 111, "name": "sale-report1" },
{ "id": 112, "name": "sale-report2" },
{
"id": 2,
"name": "webstore",
},
{
"id": 11,
"name": "sale-report",
},
{ "id": 111, "name": "webstore-report1" },
{ "id": 112, "name": "webstore-report2" },
{
"id": 2,
"name": "setting",
},
{
"id": 11,
"name": "general",
},
{ "id": 111, "name": "setting-general1" },
{ "id": 112, "name": "setting-general2" }
]
条件是如果分支中的对象内有键"detail",则也将Map该键(假设数组内的对象内的键"detail"不受限制)
注:明细内容与父项相同,但值不同
先谢了
我尝试mapping mannualy与foreach,但我不能弄清楚,如果详细键与数组(对象)有无限嵌套
3条答案
按热度按时间vxf3dgd41#
只需使用recursion即可完成此操作。
这是演示版-
fv2wmkja2#
可以对对象进行反结构化,从对象中取出
detail
,然后使用递归函数将rest对象和嵌套details数组的结果Map为平面数组。slwdgvem3#
执行此操作的非递归方法如下所示: