我不明白为什么你需要RxJS来处理你的列表。
我建议这项实施:
const source = [
{
id: 'level 1.1',
permission: true,
children: [
{
id: 'level 2.1',
permission: false,
children: [
{id: 'level 3.1'}
]
},
{
id: 'level 2.2',
permission: true,
children: [
{id: 'level 3.2'}
]
}
]
},
{
id: 'level 1.2'
},
{
id: 'level 1.3',
permission: false
}
];
const isAllow = item => {
return item.permission === undefined || item.permission;
};
const filtering = (list) => {
const listing = [];
list.forEach(item => {
// If current one have permission.
if(isAllow(item)) {
// If he have child, let process it recursively.
if(item.children && item.children.length > 0) {
item.children = filtering(item.children);
}
// Add current on to whitelisted.
listing.push(item);
}
});
return listing;
};
console.log(filtering(source));
如果您想在rxjs流上打开此列表,只需使用
map
:
of(source).pipe(map(source => filtering(source))).subscribe(console.log)
编辑一个:
基于澄清,我已经以可观察的方式完成了上述代码。
allowOnly$
)其中:
-
-
concatMap
-
filter
不允许的项目。
-
海图
又是新的
combineLatest
它们是当前项和的递归调用的组合
随意地$
以所有子对象作为参数。
-
toArray
瞧
const dummyAjaxRequest = (item) => {
return of({
...item,
permission: (item.permission === undefined || item.permission)?true:false
});
}
const allowOnly$ = items => {
return from(items).pipe(concatMap(item => {
return from(
/**
* Perform your ajax request here to find what's is allow or not.
*/
dummyAjaxRequest(item)
).pipe(
/**
* Exclude what is not allowed;
*/
filter(item => item.permission),
concatMap(item => {
/**
* If we have child, perform recursive.
*/
if (item.children) {
/**
* combine child and parent.
*/
return combineLatest(
allowOnly$(item.children), // Recursive call.
of(item)
).pipe(map(i => {
return {
...i[1], // all property of current,
children : [...i[0]] // Create new array base on allowed childrens.
};
}))
}
else {
/**
* No child, return simple observable of current item.
*/
return of(item);
}
})
);
}), toArray()); // transform stream like --|-|-|-> to --[|,|,|]->
};
of(source).pipe(concatMap(items => {
return allowOnly$(items);
})).subscribe(console.log);
重要提示所有
mergeMap
你要换成什么
海图