Javascript 如何循环嵌套数组并为每个级别插入id和parentId?
如何循环嵌套数组并为每个级别插入id和parentId 这就是我所拥有的:Javascript 如何循环嵌套数组并为每个级别插入id和parentId?,javascript,arrays,nested,Javascript,Arrays,Nested,如何循环嵌套数组并为每个级别插入id和parentId 这就是我所拥有的: { "locations": [ { "name": "Europe", "children": [ { "name": "Denmark", "children": [ {
{
"locations": [
{
"name": "Europe",
"children": [
{
"name": "Denmark",
"children": [
{
"name": "Copenhagen",
"population": [
{
"people": "602481"
}
]
}
]
},
{
"name": "South Europe",
"children": [
{
"name": "Spain",
"children": [
{
"name": "Madrid",
"population": [
{
"people": "6550000"
}
]
},
{
"name": "Barcelona",
"population": [
{
"people": "5515000"
}
]
}
]
}
]
}
]
},
{
"name": "Asia",
"children": [
{
"name": "East Asia",
"children": [
{
"name": "China",
"children": [
{
"name": "Beijing",
"population": [
{
"people": "21540000"
}
]
}
]
}
]
}
]
}
]
}
这就是我想要的:
{
"locations": [
{
"id": "AP1",
"name": "Europe",
"children": [
{
"id": "AP1.1",
"parentId": "AP1",
"name": "Denmark",
"children": [
{
"id": "AN1",
"parentId": "AP1.1",
"name": "Copenhagen",
"population": [
{
"people": "602481"
}
]
}
]
},
{
"id": "AP1.2",
"parentId": "AP1",
"name": "South Europe",
"children": [
{
"id": "AP1.2.1",
"parentId": "AP1.2",
"name": "Spain",
"children": [
{
"id": "AN2",
"parentId": "AP1.2.1",
"name": "Madrid",
"population": [
{
"people": "6550000"
}
]
},
{
"id": "AN3",
"parentId": "AP1.2.1",
"name": "Barcelona",
"population": [
{
"people": "5515000"
}
]
}
]
}
]
}
]
},
{
"id": "AP2",
"name": "Asia",
"children": [
{
"id": "AP2.1",
"parentId": "AP2",
"name": "East Asia",
"children": [
{
"id": "AP2.1.1",
"parentId": "AP2.1",
"name": "China",
"children": [
{
"id": "AN4",
"parentId": "AP2.1.1",
"name": "Beijing",
"population": [
{
"people": "21540000"
}
]
}
]
}
]
}
]
}
]
}
我对JavaScript比较陌生,我只知道如何使用基本的for循环遍历第一个数组,即欧洲和亚洲。如何在层次结构中循环执行所有操作?您可以执行以下操作:
const obj={
“地点”:[{
“名称”:“欧洲”,
“儿童”:[{
“名称”:“丹麦”,
“儿童”:[{
“名称”:“哥本哈根”,
“人口”:[{
“人”:“602481”
}]
}]
},
{
“名称”:“南欧”,
“儿童”:[{
“名称”:“西班牙”,
“儿童”:[{
“姓名”:“马德里”,
“人口”:[{
“人”:“6550000”
}]
},
{
“名称”:“巴塞罗那”,
“人口”:[{
“人”:“5515000”
}]
}
]
}]
}
]
},
{
“名称”:“亚洲”,
“儿童”:[{
“名称”:“东亚”,
“儿童”:[{
“名称”:“中国”,
“儿童”:[{
“名称”:“北京”,
“人口”:[{
“人”:“2154000”
}]
}]
}]
}]
}
]
}
函数重现(arr,prevId=未定义){
设countId=0;
arr.forEach(项目=>{
countId++;
if(prevId){
item.id=prevId+'.'.+countId;
item.parentId=prevId;
}否则{
item.id=countId.toString();
}
if('children'在item&&item.children.length>0)中){
重现(item.children,item.id);
}
});
}
复发(目标位置);
document.getElementById('output').innerHTML=JSON.stringify(obj,未定义,4)代码>
您需要一个递归(一个带有if语句的函数,在其中一种if情况下调用自己,但在另一种情况下不调用自己)。aa好的,那么您可以检查是否存在“children”,如果它包含任何内容,如果这两种情况都是真的,则在内部重复该函数。并且forEach确保所有项目都循环通过。。。聪明,我明白了,非常感谢!!!