大家好,我创建了一个多维数组,它会随着不同的深度动态变化。这就是为什么我不使用通常的方法来创建静态循环过程。
所以,这里的问题是我无法删除该数组中选定的对象。
删除特定对象之前的示例数组
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/