我有一个表示树形图的JSON,并希望将其转换为具有新结构的JSON,可以使用treant.js显示它。
它应该使用不同数量的节点。每个节点/子节点可以有0或2个子节点。这实际上是我的主要问题,如何迭代输入JSON以获得所有子项和子项而不为每个子项设置循环。
父节点的标题也仅在其子节点中表示,但我在父节点中需要它。
输入:
treeModel = {
"TreeModel": {
"AlgorithmName": "CART",
"Child": [{
"RecordCount": 47,
"Score": "1", //should be the name
"ScoreDistribution": [
[24, 23], //should be the description as string
[0.5106382978723404, 0.4893617021276596]
],
"TreeNodePredicate": {
"FieldPredID": 0,
"FieldPredName": "Attribute1", //should be the title from parent
"FieldValue": 0,
"Operator": "EQUAL",
"PredicateType": "SimplePredicate"
}
}, {
"RecordCount": 214,
"Score": "0", //should be the name
"ScoreDistribution": [
[2, 212], //should be the description as string
[0.009345794392523364, 0.9906542056074767]
],
"TreeNodePredicate": {
"FieldPredID": 0,
"FieldPredName": "Attribute1", //should be the title from parent
"FieldValue": 1,
"Operator": "EQUAL",
"PredicateType": "SimplePredicate"
}
}],
"RecordCount": 261,
"Score": "0", //should be the name
"ScoreDistribution": [
[26, 235], //should be the description as string
[0.09961685823754787, 0.9003831417624522]
],
"TreeNodePredicate": {
"PredicateType": "TruePredicate"
}
}
}
输出:
chart_config = {
chart: {
container: "#tree-simple"
},
nodeStructure: {
text: {
name: "0" , //Score
title: "Attribute1", //FieldPredName from Child
desc: "26, 235", //ScoreDistribution as String
},
children: [
{
text: {
name: "1" , //Score
title: "", //FieldPredName from Child(empty as no childs)
desc: "24, 23", //ScoreDistribution as String
}
},
{
text: {
name: "0" , //Score
title: "", //FieldPredName from Child(empty as no childs
desc: "2, 212", //ScoreDistribution as String
}
}
]
}
};
答案 0 :(得分:0)
您可以使用递归和迭代方法进行转换。
function convert(source) {
var target = {
text: {
name: source.Score,
title: source.Child && source.Child[0] && source.Child[0].TreeNodePredicate && source.Child[0].TreeNodePredicate.FieldPredName || '',
desc: source.ScoreDistribution[0].join(', ')
}
};
if (Array.isArray(source.Child)) {
target.children = source.Child.map(convert);
}
return target;
}
var treeModel = { TreeModel: { AlgorithmName: "CART", Child: [{ RecordCount: 47, Score: "1", ScoreDistribution: [[24, 23], [0.5106382978723404, 0.4893617021276596]], TreeNodePredicate: { FieldPredID: 0, FieldPredName: "Attribute1", FieldValue: 0, Operator: "EQUAL", PredicateType: "SimplePredicate" } }, { RecordCount: 214, Score: "0", ScoreDistribution: [[2, 212], [0.009345794392523364, 0.9906542056074767]], TreeNodePredicate: { FieldPredID: 0, FieldPredName: "Attribute1", FieldValue: 1, Operator: "EQUAL", PredicateType: "SimplePredicate" } }], RecordCount: 261, Score: "0", ScoreDistribution: [[26, 235], [0.09961685823754787, 0.9003831417624522]], TreeNodePredicate: { PredicateType: "TruePredicate" } } },
chart_config = { chart: { container: "#tree-simple" }, nodeStructure: convert(treeModel.TreeModel) };
console.log(chart_config);

.as-console-wrapper { max-height: 100% !important; top: 0; }