过滤嵌套的树对象而不会丢失结构 [英] filter nested tree object without losing structure
问题描述
我有嵌套的树对象我希望过滤而不会丢失结构
I have nested tree object I would like filter through without losing structure
var items = [
{
name: "a1",
id: 1,
children: [{
name: "a2",
id: 2,
children: [{
name: "a3",
id: 3
}]
}]
}
];
所以例如如果id == 2删除id为2的对象和他的孩子
so for example if id == 2 remove object with id 2 and his children
如果id == 3只删除id为3的对象
if id == 3 only remove object with id 3
这只是对象的一部分,可以使问题干净但是它自己的对象包含越来越多:)
this's just apiece of object to make question clean but the object it self contains more and more :)
使用vanilla javascript,_lodash或Angular2它没关系
using vanilla javascript, _lodash or Angular2 it's okay
谢谢
推荐答案
您可以使用 filter()
创建递归函数,并且还可以继续过滤子项value是Array。
You can create recursive function using filter()
and also continue filtering children if value is Array.
var items = [{
name: "a1",
id: 1,
children: [{
name: "a2",
id: 2,
children: [{
name: "a3",
id: 3
}, ]
}]
}];
function filterData(data, id) {
var r = data.filter(function(o) {
Object.keys(o).forEach(function(e) {
if (Array.isArray(o[e])) o[e] = filterData(o[e], id);
})
return o.id != id
})
return r;
}
console.log(filterData(items, 3))
console.log(filterData(items, 2))
更新:正如Nina所说,如果你知道孩子是带阵列的属性,你不需要循环键就可以直接定位 children
property。
Update: As Nina said if you know that children is property with array you don't need to loop keys you can directly target children
property.
var items = [{
name: "a1",
id: 1,
children: [{
name: "a2",
id: 2,
children: [{
name: "a3",
id: 3
}, ]
}]
}];
function filterData(data, id) {
var r = data.filter(function(o) {
if (o.children) o.children = filterData(o.children, id);
return o.id != id
})
return r;
}
console.log(JSON.stringify(filterData(items, 3), 0, 4))
console.log(JSON.stringify(filterData(items, 2), 0, 4))
这篇关于过滤嵌套的树对象而不会丢失结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!