【发布时间】:2022-01-13 17:21:56
【问题描述】:
我有这个 JSON 对象数组:
我想为每个条目添加一个唯一的 ID(字符串),如下所示:
let myTree = [
{
text: 'Batteries',
id: '0',
children: [
{
text: 'BatteryCharge',
id: '0-0'
},
{
text: 'LiIonBattery',
id: '0-1'
}
]
},
{
text: 'Supplemental',
id: '1',
children: [
{
text: 'LidarSensor',
id: '1-0',
children: [
{
text: 'Side',
id: '1-0-0'
},
{
text: 'Tower',
id: '1-0-1'
}
]
}
]
}
]
我只是想不出实现这一目标的正确逻辑。我写了这个递归函数,显然没有达到我想要的效果:
function addUniqueID(tree, id=0) {
if(typeof(tree) == "object"){
// if the object is not an array
if(tree.length == undefined){
tree['id'] = String(id);
}
for(let key in tree) {
addUniqueID(tree[key], id++);
}
}
}
addUniqueID(myTree);
我该如何解决这个问题?
【问题讨论】:
-
我建议尝试像 UUID 这样的包。但是,如果这些数据进入像 Mongo 或 SQL 这样的数据库,它们将被自动识别,你必须遵循他们的 ID 系统规则。
-
因此,JSON 对象本质上是目录树。数据不会进入数据库。我需要根据我描述的格式将 ID 添加到每个 JSON 对象,因为这些 ID 然后会被解析以获取每个子目录的路径。
标签: javascript node.js arrays json