Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/467.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
Javascript 使用NodeJS按属性排序嵌套JSON_Javascript_Json_Node.js - Fatal编程技术网

Javascript 使用NodeJS按属性排序嵌套JSON

Javascript 使用NodeJS按属性排序嵌套JSON,javascript,json,node.js,Javascript,Json,Node.js,假设我有这样一个目录结构: root |_ .git |_ .sass-cache |_ css | |_ scss | | |_ modules | | | |_ a-module.scss | | | |_ ... | | |_ partials | | | |_ a-partial.scss | | | |_ ... | | |_ main.scss | |_ main.css | |_ main.css.map ... |_ .bowerrc

假设我有这样一个目录结构:

root
|_ .git
|_ .sass-cache
|_ css
|  |_ scss
|  |  |_ modules
|  |  |  |_ a-module.scss
|  |  |  |_ ...
|  |  |_ partials
|  |  |  |_ a-partial.scss
|  |  |  |_ ...
|  |  |_ main.scss
|  |_ main.css
|  |_ main.css.map

...

|_ .bowerrc
|_ .gitignore
|_ app.js
|_ bower.json
|_ Gruntfile.js
|_ index.html
|_ package.json
|_ README.md
我正在使用下面的代码生成这种结构的JSON,但它还没有保持我想要的顺序,如上图所示,文件夹位于列表的顶部(按字母顺序),文件位于列表的底部(也按字母顺序)

(根据答案修改)

这将以以下格式输出JSON:

{
    path: '/absolute/path/to/directory',
    name: 'name-of-dir',
    type: 'directory',
    children:
        [
            {
                path: '/absolute/path/to/file',
                name: 'name-of-file',
                type: 'file',
            },
            {
                path: '/absolute/path/to/directory',
                name: 'name-of-dir',
                type: 'directory',
                children:
                    [
                        {
                            ...
                        }
                    ]
            }
        ]
}
我想知道如何最好地修改现有代码,对
子数组进行排序,以复制目录结构顺序。检查应该使用
名称
类型
属性来确定其在结果JSON中的位置


非常感谢使用
Array.prototype.sort

    info.children = fs.readdirSync(filepath).map(function(child) {
        return getTree(path.join(filepath, child));
    });

    info.children.sort( function(a,b) {
        // Directory index low file index
        if (a.type === "directory" && b.type === "file") return -1;
        if (b.type === "directory" && a.type === "file") return 1;

        return a.path.localeCompare(b.path);
    });

创建平面列表?或者只是对每个子节点单独排序?您可以递归调用
obj.nodes.sort
。只是把孩子们分类。
    info.children = fs.readdirSync(filepath).map(function(child) {
        return getTree(path.join(filepath, child));
    });

    info.children.sort( function(a,b) {
        // Directory index low file index
        if (a.type === "directory" && b.type === "file") return -1;
        if (b.type === "directory" && a.type === "file") return 1;

        return a.path.localeCompare(b.path);
    });