【发布时间】:2017-07-02 00:19:58
【问题描述】:
根据我最初专门针对 React (React recursive tree pass JSON path) 提出的问题,我意识到这个问题非常普遍。
我有一个递归函数,它本质上循环遍历树状 JSON 结构,每次它输出一个分支时,我想传递树中结构位置的对象,如下所示。有没有更简单的方法来传递结构?数据结构是否糟糕/每个孩子都应该附加一个唯一的 ID 吗?
我的 JSON 对象在下面,因此您可以看到我正在处理的内容。
非常感谢任何帮助!
1 级孩子
{值:“水果”}
2 级孩子
{value: "水果", nested_values: [{ value: 'Tropical'}] }
3 级孩子
{value: "水果", nested_values: [{ value: '热带', nested_values:[{ value: '菠萝' }]}] }
代码 - 有点工作,但我在同一个 nested_values 数组中获取所有值
const createSelectionHierarchy = (data, isSub, level = 2, hierarchy = {}) => {
let children = [];
if (isSub) { level++; }
let obj = {};
obj.name = cat;
const cat = hierarchy.value;
for (let i in data) {
const subcat = data[i].value;
if (typeof(data[i].nested_values) === 'object') { // Sub array found, build structure
obj.values = subcat;
obj.nested_values = [];
hierarchy.nested_values.push(obj);
children.push(
<FilterItem key={i} data={data[i]} hierarchy={hierarchy} level={level}>
{createSelectionHierarchy(data[i].nested_values, true, level, hierarchy)}
</FilterItem>
);
} else { // No sub array, bottom of current branch
children.push(
<p className="filter-item level-last" key={i}>
{data[i].value}
</p>);
}
}
return children;
}
JSON
{
"value": "Fruit",
"occurrence_count": 5,
"nested_values": [{
"value": "Berries",
"occurrence_count": 3,
"nested_values": [{
"value": "Strawberry",
"occurrence_count": 1
}, {
"value": "Blackberry",
"occurrence_count": 1
}, {
"value": "Raspberry",
"occurrence_count": 1
}, {
"value": "Redcurrant",
"occurrence_count": 1
}, {
"value": "Blackcurrant",
"occurrence_count": 1
}, {
"value": "Gooseberry",
"occurrence_count": 1
}, {
"value": "Cranberry",
"occurrence_count": 1
}, {
"value": "Whitecurrant",
"occurrence_count": 1
}, {
"value": "Loganberry",
"occurrence_count": 1
}, {
"value": "Strawberry",
"occurrence_count": 1
}]
}, {
"value": "Tropical",
"occurrence_count": 2,
"nested_values": [{
"value": "Pineapple",
"occurrence_count": 1
}, {
"value": "Mango",
"occurrence_count": 1
}, {
"value": "Guava",
"occurrence_count": 1
}, {
"value": "Passion Fruit",
"occurrence_count": 1
}, {
"value": "Dragon Fruit",
"occurrence_count": 1
}]
}]
}
期望的输出
<FilterItem ...... hierarchy={{value: "Fruit"}}>
<FilterItem ...... hierarchy={{value: "Fruit", nested_values: [{ value: 'Tropical'}] }}>
<FilterItem ...... hierarchy={{value: "Fruit", nested_values: [{ value: 'Tropical', nested_values:[{ value: 'Pineapple' }]}] }}>
</FilterItem>
</FilterItem>
</FilterItem>
【问题讨论】:
-
@r1verside - 你有例子吗?
-
@ibrahimmahrir - 我更新了我的答案
-
你有 JavaScript(意思是 ECMA 脚本)版本的代码吗?
-
@Traktor53 - 不幸的是不是,但上面的内容很容易破译吗?它只是一个函数,唯一奇怪的是我将 JSX 元素推入数组而不是对象
-
@Zinc 请看一下我的回答,看看您是否想要。如果有,我会添加解释。
标签: javascript json recursion ecmascript-6