【问题标题】:Order nested JSON by property using NodeJS使用 NodeJS 按属性对嵌套 JSON 进行排序
【发布时间】:2015-10-20 09:19:00
【问题描述】:

假设我有这样的目录结构:

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,但它尚未保持我想要的顺序,如上所示,文件夹位于列表顶部(按字母顺序),文件位于位于列表底部(也按字母顺序)。

var fs = require('fs');
var path = require('path');

function getTree(filepath) {

    filepath = path.normalize(filepath);

    var stats = fs.lstatSync(filepath);
    var info = {
        path: filepath,
        name: path.basename(filepath)
    };

    if (stats.isDirectory()) {
        info.type = "directory";
        info.children = fs.readdirSync(filepath).map(function(child) {
            return getTree(path.join(filepath, child));
        });
    } else {
        info.type = "file";
    }
    return info;
}

exports.getTree = getTree;

(修改自this答案)

这会以以下格式输出 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:
                    [
                        {
                            ...
                        }
                    ]
            }
        ]
}

我想知道如何最好地更改现有代码以对children 数组进行排序以复制目录结构顺序。检查应使用nametype 属性来确定其在结果JSON 中的位置。

非常感谢

【问题讨论】:

标签: javascript json node.js


【解决方案1】:

使用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);
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 1970-01-01
    • 2018-07-03
    • 1970-01-01
    相关资源
    最近更新 更多