javascript - 删除嵌套数组中的某一项

查看:120
本文介绍了javascript - 删除嵌套数组中的某一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

[{
        "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来删除数组中的某一项,数组长度不确定,是嵌套的,知道用递归。。但是不会写,哪位能帮忙写下。。

解决方案

这样应该就可以了,你试试

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">

function call(arr,tag){
  for(var i = arr.length ; i > 0 ; i--){
      if(arr[i-1].id == tag){
        arr.splice(i-1,1);
      }else{
        if(arr[i-1].children){
          call(arr[i-1].children,tag)
        }
      }
  }
}
var arr = [{
'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'
      },
    ]
  }
]

}];

call(arr,2);
console.dir(arr);

</script>
</body>
</html>

这篇关于javascript - 删除嵌套数组中的某一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆