删除嵌套数组中的某一项

[{

        "title": "parent",

        "expanded": true,

        "folder": true,

        "id": "0",

        "children": [

          {

            "title": "parent[0]",

            "expanded": true,

            "folder": true,

            "id": "1",

            "children": [

              {"title": "Books",  "id": "2"},

              {"title": "Kindle Books",  "id": "3"},

              {"title": "Books For Study",  "id": "4"},

              {"title": "Audiobooks",  "id":"5"}

            ]

          },

          {

            "title": "parent[1]", "id": "6", "folder": true, "children": [

            {"title": "Music", "id": "7"},

            {"title": "MP3 Downloads", "id": "8"},

            {"title": "Musical Instruments & DJ", "id": "9"},  

          ]

          }

        ]

      }]

想根据id来删除数组中的某一项,数组长度不确定,是嵌套的,知道用递归。。但是不会写,哪位能帮忙写下。。


翻翻过去那场雪
浏览 731回答 1
1回答

收到一只叮咚

这样应该就可以了,你试试<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Document</title></head><body><script type="text/javascript">function call(arr,tag){&nbsp; for(var i = arr.length ; i > 0 ; i--){&nbsp; &nbsp; &nbsp; if(arr[i-1].id == tag){&nbsp; &nbsp; &nbsp; &nbsp; arr.splice(i-1,1);&nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; if(arr[i-1].children){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; call(arr[i-1].children,tag)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; }}var arr = [{'title': 'parent','expanded': true,'folder': true,'id': '0','children': [&nbsp; {&nbsp; &nbsp; 'title': 'parent[0]',&nbsp; &nbsp; 'expanded': true,&nbsp; &nbsp; 'folder': true,&nbsp; &nbsp; 'id': '1',&nbsp; &nbsp; 'children': [&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Books',&nbsp; &nbsp; &nbsp; &nbsp; 'id': '2'&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Kindle Books',&nbsp; &nbsp; &nbsp; &nbsp; 'id': '3'&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Books For Study',&nbsp; &nbsp; &nbsp; &nbsp; 'id': '4'&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Audiobooks',&nbsp; &nbsp; &nbsp; &nbsp; 'id': '5'&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; ]&nbsp; },&nbsp; {&nbsp; &nbsp; 'title': 'parent[1]',&nbsp; &nbsp; 'id': '6',&nbsp; &nbsp; 'folder': true,&nbsp; &nbsp; 'children': [&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Music',&nbsp; &nbsp; &nbsp; &nbsp; 'id': '7'&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'MP3 Downloads',&nbsp; &nbsp; &nbsp; &nbsp; 'id': '8'&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Musical Instruments & DJ',&nbsp; &nbsp; &nbsp; &nbsp; 'id': '9'&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; ]&nbsp; }]}];call(arr,2); console.dir(arr);</script></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript