动态嵌套对象循环js

时间:2017-09-28 18:23:20

标签: javascript json loops nested

这是我想循环的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
                   }]
          }]
    }

1 个答案:

答案 0 :(得分:0)

您可以使用递归函数执行此操作:

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);