【发布时间】:2019-04-11 11:25:02
【问题描述】:
我有一个场景是我需要遍历对象中的每个父/子数组。
每个祖父母可以有多个父母,以同样的方式每个父母可以有多个孩子,每个孩子可以有多个子孩子等等。
我需要在迭代时检查类型是“父”还是“子”,然后将 name 属性推送到预期输出中提到的数组。
输入对象:
var inputObject = {
"id": 1,
"name": "Grand Parent 1",
"type": "GrandParent",
"childType": [
{
"id": 2,
"type": "Parent",
"childType": [
{
"id": 3,
"type": "Child",
"childType": [],
"name": "Child 11"
},
{
"id": 4,
"type": "Child",
"childType": [],
"name": "Child 12"
}
],
"name": "Parent 1"
},
{
"id": 5,
"type": "Parent",
"childType": [
{
"id": 6,
"type": "Child",
"childType": [],
"name": "Child 21"
}
],
"name": "Parent 2"
},
{
"id": 7,
"type": "Parent",
"childType": [
{
"id": 8,
"type": "Child",
"childType": [],
"name": "Child 31"
}
],
"name": "Parent 3"
}
]
}
代码尝试:
function handleData({childType, ...rest}){
const res = [];
res.push(rest.name);
if(childType){
if(rest.type == "Child")
res.push(...handleData(childType));
}
return res;
}
const res = handleData(inputObject);
预期输出:
If type selected is "Parent"
["Parent 1", "Parent 2, Parent 3"]
if type selected is "Child"
["Child 11", "Child 12", "Child 21", "Child 31"]
【问题讨论】:
标签: javascript arrays javascript-objects