javascript - 动态嵌套对象循环js

标签 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
                   }]
          }]
    }

最佳答案

您可以使用递归函数来完成:

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/

相关文章:

javascript - Flex slider 无法正常工作 最后一张幻灯片

arrays - 检查一个数组是否包含另一个数组的所有值(是否所有用户都分配了工作?)

bash - 如何在 Bash 中同时循环两个文件(一个文本文件,一个json文件)?

javascript - 使用 for 循环添加到数组时对语法感到困惑

javascript:如何将字符串数组转换为连接以逗号分隔的项目的纯字符串?

javascript - 如何转换此日期格式:/Date(1268524800000)/?

json - Swift 4 可编码 : the keys are Int array in JSON data

php - 从 PHP 返回两个 2 json 对象

在列表中拉出特定间隔的开始/结束的 Pythonic 方法?

javascript - 如何在数据库响应之前延迟函数返回值?