[英]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.