Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何使用RxJs执行嵌套reduce操作?_Angular_Typescript_Rxjs - Fatal编程技术网

Angular 如何使用RxJs执行嵌套reduce操作?

Angular 如何使用RxJs执行嵌套reduce操作?,angular,typescript,rxjs,Angular,Typescript,Rxjs,我试图将一系列文件路径变形为角度材质的嵌套递归结构。结构需要如下所示: interface FileTreeNode { name: string; children?: FileTreeNode[]; } 因此,文件路径列表,如['path/to/file/01.txt'、'path/to/file/02.txt'、'other/to/file/03.txt']将转换为: [ {name: 'path', children: [ {name: 'to'

我试图将一系列文件路径变形为角度材质的嵌套递归结构。结构需要如下所示:

interface FileTreeNode {
    name: string;
    children?: FileTreeNode[];
}
因此,文件路径列表,如
['path/to/file/01.txt'、'path/to/file/02.txt'、'other/to/file/03.txt']
将转换为:

[
    {name: 'path', children: [
        {name: 'to', children: [
            {name: 'file', children: [
                {name: '01.txt'}, {name: '02.txt'}
                ]
            }]
        }]
    },
    {name: 'another', children: [
        {name: 'to', children: [
            {name: 'file', children: [
                {name: '03.txt'}
                ]
            }]
        }]
    }
]
对于这个问题,我看到了一个很好的答案,它使用了内置的
Array.reduce()
方法,但我想用RxJs操作符来完成这一点

以下是我试图复制的代码:

var paths = ["path/to/file1.doc", "path/to/file2.doc", "foo/bar.doc"],
    result = [];
    
paths.reduce((r, path) => {
    path.split('/').reduce((o, name) => {
        var temp = (o.children = o.children || []).find(q => q.name === name);
        if (!temp) o.children.push(temp = { name });
        return temp;
    }, r);
    return r;
}, { children: result });

console.log(result);
以下是我目前掌握的情况:

reduce((acc, curr) => {
    return curr.split('/').reduce((obj, name) => {
        let temp = (obj.children != null ? obj.children : obj.children = []).find(node => node.name === name);
        if (temp == null) {
            obj.children.push(temp = {name});
        }
        return temp;
    }, acc);
}, {children: []} as FileTreeNode),
但这只是返回可观察对象中的最后一个节点(例如,
{name:03.txt}
)。我想要传递的是
acc
的最终值,就像上面的代码一样。我还希望只使用RxJs操作符来完成这一点,而不必依赖内部的Js
Array.reduce()
函数(如果可能的话)


谢谢

使用reduce的方法与此完全相同,不同之处在于需要将数组转换为流。您可以使用来自操作员的

path=[“path/to/file1.doc”、“path/to/file2.doc”、“foo/bar.doc”];
路径$=来自(this.paths).pipe(
减少(
(r,路径)=>{
path.split(“/”).reduce((o,name)=>{
var temp=(o.children=o.children | |[]).find(q=>q.name==name);
如果(!temp)o.children.push((temp={name}));
返回温度;
},r);
返回r;
},
{儿童:[]}
)
);

请参见

这是一个有趣的练习,但是除非您有一个异步的文件路径段流,否则您应该坚持使用
Array.prototype.reduce
谢谢。问题是我的声纳线头乱了,因为我没有返回reduce的值,而是返回累加器对象。这就是为什么我不去做
返回r语句。