我有一个Web服务,它从db上的select返回一个json。 问题是这种对象是层次结构的一部分,其中每个子节点都与父节点连接,并带有一个名为“idCdcParent”的字段。 根元素是idCdcParent为null的位置。 在这种情况下,罗马,米兰和那不勒斯是根本元素。 这是json:
[{
"idCdc": "2",
"cdcName": "Roma",
"order": "1",
"isUsed": "false"
}, {
"idCdc": "17",
"idCdcParent": "5",
"cdcName": "testGP",
"order": "1",
"isUsed": "false"
}, {
"idCdc": "5",
"idCdcParent": "2",
"cdcName": "Progetti",
"order": "2",
"isUsed": "false"
}, {
"idCdc": "18",
"idCdcParent": "5",
"cdcName": "testGPS",
"order": "2",
"isUsed": "false"
}, {
"idCdc": "3",
"cdcName": "Milano",
"order": "4",
"isUsed": "false"
}, {
"idCdc": "7",
"idCdcParent": "3",
"cdcName": "l",
"order": "4",
"isUsed": "false"
}, {
"idCdc": "4",
"cdcName": "Napoli",
"order": "5",
"isUsed": "false"
}, {
"idCdc": "9",
"idCdcParent": "4",
"cdcName": "cccc",
"order": "6",
"isUsed": "false"
}]
我希望它是一个具有层次结构的json,其中字段“idCdcParent”指的是父对象的id。 像这样:
[{
"idCdc": "2",
"cdcName": "Roma",
"order": "1",
"isUsed": "false",
"children": [{
"idCdc": "5",
"idCdcParent": "2",
"cdcName": "Progetti",
"order": "2",
"isUsed": "false"
},
{
"idCdc": "17",
"idCdcParent": "5",
"cdcName": "testGP",
"order": "1",
"isUsed": "false"
}
]
},
{
"idCdc": "5",
"idCdcParent": "2",
"cdcName": "Progetti",
"order": "2",
"isUsed": "false"
},
{
"idCdc": "3",
"cdcName": "Milano",
"order": "4",
"isUsed": "false",
"children": [{
"idCdc": "7",
"idCdcParent": "3",
"cdcName": "l",
"order": "4",
"isUsed": "false"
}]
},
{
"idCdc": "4",
"cdcName": "Napoli",
"order": "5",
"isUsed": "false",
"children": [{
"idCdc": "9",
"idCdcParent": "4",
"cdcName": "cccc",
"order": "6",
"isUsed": "false"
}]
}
]
在javascript中可能吗? 谢谢
答案 0 :(得分:0)
确定有可能,只需遍历数组并为id建立一个查找表:
const byID = {};
for(const el of array)
byId[el.idCdc] = el;
现在您已经获得了查找表,它很容易遍历节点,并将它们转换为层次结构:
let root;
for(const el of array) {
if(el.idCdcParent) {
const parent = byID[el.idCdcParent];
if(!parent.children) parent.children = [];
parent.children.push(el);
} else {
root = el;
}
}
答案 1 :(得分:0)
您可以使用递归函数将实体数组转换为树。此方法创建新数组的层次结构实体,并且原始版本未被修改 - 可能是加号或减号,具体取决于您的特定用例:
function make_tree(treeable_entities) {
function TreeNode(entity) {
const children = get_children(entity.idCdc);
const new_entity = Object.assign({}, entity);
new_entity.children = children;
return new_entity;
}
function get_children(ofIdentifier) {
return treeable_entities.filter(entity => entity.idCdcParent === ofIdentifier).map(TreeNode);
}
const is_root = (entity) => entity. idCdcParent === undefined;
return treeable_entities.filter(is_root).map(TreeNode);
};