使用NodeJS按属性对嵌套的JSON进行排序 [英] Order nested JSON by property using NodeJS
问题描述
假设我有这样的目录结构:
Say I have a directory structure like this:
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,但它还没有维护我想要的顺序,如上所示文件夹位于列表顶部(按字母顺序排列),文件位于列表底部(也按字母顺序排列)。
I am using the following code to generate JSON of this structure but it doesn't yet maintain the ordering I'd like as shown above with folders being positioned at the top of the list (in alphabetical order) and the files being positioned at the bottom of the list (also in alphabetical order).
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;
(修改自这个答案)
这会以下列格式吐出JSON:
This spits out JSON in the following format:
{
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:
[
{
...
}
]
}
]
}
我想知道怎么样st来改变我现有的代码来对 children
数组进行排序以复制目录结构顺序。检查应使用名称
和类型
属性来确定其在结果JSON中的位置。
I'd like to know how best to go about altering my existing code to sort the children
arrays to replicate the directory structure order. The check should use the name
and type
properties to determine its location in the resultant 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);
});
这篇关于使用NodeJS按属性对嵌套的JSON进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!