javascript - jQuery - 删除多维数组中选定对象的方法

标签 javascript jquery arrays

大家好,我创建了一个多维数组,它会随着不同的深度动态变化。这就是为什么我不使用通常的方法来创建静态循环过程。

所以,这里的问题是我无法删除该数组中选定的对象。

删除特定对象之前的示例数组

var data = [
  {
    id:"43",
    text: 'Parent 1'
  },
  {
    id:"55",
    text: 'Parent 2',
    nodes: [
      {
        id:"57",
        text: 'Child 1',
        nodes: [
          {
            id:"56",
            text: 'Child sub 2'
          },
          {
            id:"50",
            text: 'Child sub 3'
          }
        ]
      }
    ]
  },
  {
    id:"47",
    text: 'Parent 3',
    nodes: [
      {
        id:"48",
        text: 'Child 2'
      }
    ]
  }
]

例如,如果我选择了 setence 对象,当前数组将保持如下

  {
    id:"50",
    text: 'Child sub 3'
  } 

预期结果

   var data = [
          {
            id:"43",
            text: 'Parent 1'
          },
          {
            id:"55",
            text: 'Parent 2',
            nodes: [
              {
                id:"57",
                text: 'Child 1',
                nodes: [
                  {
                    id:"56",
                    text: 'Child sub 2'
                  }
                ]
              }
            ]
          },
          {
            id:"47",
            text: 'Parent 3',
            nodes: [
              {
                id:"48",
                text: 'Child 2'
              }
            ]
          }
        ]

我的jsfiddle中的示例代码

最佳答案

这是一种方法,假设您的数据格式没有改变:

// using your previously-defined data variable

var query = {
  key: 'id',
  value: 50
};

function removeMatchedObjectFromArray(source, query) {
  query.parent = query.parent || source;
  for (var key in source) {
    if (!source.hasOwnProperty(key)) {
      continue;
    }
    if (typeof source[key] === 'object') {
      if (source[key] && source[key] instanceof Array) {
        query.parent = source[key];
      }
      removeMatchedObjectFromArray(source[key], query);
    } else if (key == query.key && source[key] == query.value) {
      query.parent.splice(query.parent.indexOf(source), 1);
    }
  }
}

removeMatchedObjectFromArray(data, query);

关于javascript - jQuery - 删除多维数组中选定对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38596509/

相关文章:

javascript - 无法在 jstree 中看到文件夹名称。仅显示图标

javascript - 在 event.preventDefault() 之后启用按钮默认值

c - 扫描指针数组问题

arrays - C、从单个输入行读取多个数字

java - 如何将单维索引转换为多维数组中的相应索引?

javascript - 如何在同一存储库上使用 React.js 和 Node.js

javascript - AngularJS 如何从另一个 Controller 调用 div 上的 ng-show

javascript - 渐进式加载代码片段不太了解

javascript - 尝试阻止页面重新加载时,提交按钮和表单不起作用

javascript - $.getJSON 在 Internet Explorer 中不工作