我正在尝试使用下面的json对象数组创建一个类别树.我希望将一个类别设置为另一个类别的子类,如果它的父级等于另一个类别的id,我希望帖子也是该类别的子级而不是为帖子设置单独的字段,我会添加一个标志字段,如果它是一个类别或不isParent.
看起来它的工作正常,但正如您所看到的,如果某个类别同时包含类别和帖子作为子项,则它仅显示类别.另一个问题是如果帖子在其数组上具有空值,它仍然会将它们作为子项推送.
我的代码中有哪些错误,或者是否有更简单或更好的解决方案?
var tree = unflatten(getData());
var pre = document.createElement('pre');
console.log(tree);
pre.innerText = JSON.stringify(tree, null, 4);
document.body.appendChild(pre);
function unflatten(array, parent, tree) {
tree = typeof tree !== 'undefined' ? tree : [];
parent = typeof parent !== 'undefined' ? parent : {
id: 0
};
_.map(array, function(arr) {
_.set(arr, 'isParent', true);
});
var children = _.filter(array, function(child) {
return child.parent == parent.id;
});
if (!_.isEmpty(children)) {
if (parent.id == 0) {
tree = children;
} else { …Run Code Online (Sandbox Code Playgroud)请看看我的代码:
#include <iostream>
using std::cin; // I would like to make cin object available
using std::cout; // I would like to make cout object available in source code
using std::get; // I would like to make cin.get() available
using std::fail; // I would like to make cin.fail() available
factorial(int number);
int main()
{
int closer;
cin >> closer;
while (!cin.fail())
{
factorial(closer); // it's obvious going by the name, It's factorial function
cin >> closer;
}
}
factorial(int number)
{ …Run Code Online (Sandbox Code Playgroud)