这是一个我想要循环的 json 对象:
{
node: 'tree',
text: 'Main Node',
childs:[
{
node: 'tree',
text: 'First Child',
childs:[{
node: 'tree',
text: 'first child child'
}....]
},{
node: 'tree',
text: '2nd Child',
childs:[{
node: 'tree',
text: '2nd child child'
}...]
}...]
}
这里是第一种json。但问题是 json 是动态的,子元素会根据不同的条件而变化。所以我想循环遍历 json 并将 leaf: true 添加到最后一个嵌套元素的末尾。 这就是想要的:
{
node: 'tree',
text: 'Main Node',
childs:[
{
node: 'tree',
text: 'First Child',
childs:[{
node: 'tree',
text: 'first child child',
leaf: true // i want to add this node to every last one
}]
},{
node: 'tree',
text: '2nd Child',
childs:[{
node: 'tree',
text: '2nd child child',
leaf: true
}]
}]
}
最佳答案
您可以使用递归函数来完成:
let objt = {
node: 'tree',
text: 'Main Node',
childs: [
{
node: 'tree',
text: 'First Child',
childs: [{
node: 'tree',
text: 'Main Node'
}]
}, {
node: 'tree',
text: '2nd Child',
childs: [{
node: 'tree',
text: '2nd child child'
}]
}]
};
function setLeaf(objt) {
if (!objt.childs) {
objt.leaf = true;
} else {
objt.childs.forEach(child => setLeaf(child))
}
}
setLeaf(objt);
关于javascript - 动态嵌套对象循环js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46475928/