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