【问题标题】:Iterate through a json with hierarchical children and add a key value pair遍历具有分层子级的 json 并添加键值对
【发布时间】:2019-06-12 15:50:30
【问题描述】:

我想将现有数据转换为其他数据。请在下面找到现有代码和预期代码。

现有:

{ “标题”:“标题1”, “孩子”: [ { “标题”:“标题”, “孩子”: [ { “标题”:“测试”, “孩子”: [ { "title": "testchild",

            },
           {
              "title": "Descriptionchild",
            }
             ]

            },
            {
                "title": "Description",
            }
        ]
    }
]

}

预期:

{ “标题”:“标题1”, “customId”:“title1-xx” “孩子”: [ { “标题”:“标题”, "customId": "Header1-xx", “孩子”: [ { “标题”:“测试”, "customId": "test1-xx", “孩子”: [ { "title": "testchild", "customId": "testchild1-xx"

                        },
                        {
                            "title": "Descriptionchild",
                            "customId": "Descriptionchild1-xx"
                        }
                    ]

            },
            {
                "title": "Description",
                "customId": "Description1-xx"
            }
        ]
    }
]

}

【问题讨论】:

  • 你从哪里得到缺失值?请添加您的尝试。

标签: javascript arrays json object tree


【解决方案1】:

我们可以定义一个函数,它接受一个数组并递归地添加这个属性:

// input must be array
function recursivelyAddCustomId(input) {
  // if input is not empty i.e. child is not empty
  if (input != null) {
    // for each child object in array
    for (let obj of input) {
      // set custom id
      if (obj.title != null) {
        obj.customId = obj.title + '-xx';
      }
      // recurse (doesn't matter if child exists)
      recursivelyAddCustomId(obj.child);
    }
  }
}
// put input as array
recursivelyAddCustomId([input]);
console.log(input);

请注意,此函数的输入必须是数组,因此必须先将第一个对象转换为数组。

如果有什么我需要澄清的,请告诉我。

注意:注释是在代码块中进行的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 2017-06-07
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 1970-01-01
    相关资源
    最近更新 更多