[英]How to add a unique ID to each entry in my JSON object?
我有这个 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,显然没有达到我想要的:
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);
我怎么解决这个问题?
我没有在递归 function 中使用数字/id,而是构建了一个字符串。
let myTree = [{ text: 'Batteries', children: [{ text: 'BatteryCharge' }, { text: 'LiIonBattery' } ] }, { text: 'Supplemental', children: [{ text: 'LidarSensor', children: [{ text: 'Side' }, { text: 'Tower' } ] }] } ]; function addUniqueID(arr, idstr = '') { arr.forEach((obj, i) => { obj.id = `${idstr}${i}`; if (obj.children) { addUniqueID(obj.children, `${obj.id}-`); } }); } addUniqueID(myTree); console.log(myTree);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.