【问题标题】:How to add a unique ID to each entry in my JSON object?如何为我的 JSON 对象中的每个条目添加唯一 ID?
【发布时间】: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


【解决方案1】:

我没有在递归函数中使用数字/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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多