我有以下对象的数组
{
id: 'a',
parent_id: 'root'
}
{
id: 'a1',
parent_id: 'a'
}
{
id: 'a11',
parent_id: 'a1'
}
{
id: 'a12',
parent_id: 'a1'
}
{
id: 'a13',
parent_id: 'a1'
}
.
.
.
.
.
{
id: 'a2',
parent_id: 'a'
}
{
id: 'a21',
parent_id: 'a2'
}
{
id: 'a22',
parent_id: 'a2'
}
{
id: 'a23',
parent_id: 'a2'
}
.
.
.
.
.
我有一个ID为
a
的根元素,它有多个子代(子代保存为parent_id
属性)我在mongodb中以相同的格式保存。我想与其他用户共享相同的记录,并且
我的数据模型需要这些ID是唯一的,因此我只想将这些对象数组复制到一个单独的var中,然后将这些id更改为保持父级和子级关系的随机字符串。
我现在可以使用
Random.id()
从其中一个库中生成随机字符串,现在我还不知道如何遍历所有子级并更改id
和parent_id
属性,对此不胜感激。谢谢。
最佳答案
我想这可能就是您想要的;
function makeUniqueId(){
var id = "",
charList = "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
numList = "0123456789";
for( var i=0; i < 2; i++ ) id += charList.charAt(Math.floor(Math.random() * charList.length));
for( var j=0; j < 3; j++ ) id += numList.charAt(Math.floor(Math.random() * 10));
return !~uil.indexOf(id) ? (uil.push(id),id) : makeId();
}
var uil = [], // unique id list
data = [
{
id: 'a',
parent_id: 'root'
},{
id: 'a1',
parent_id: 'a'
},{
id: 'a11',
parent_id: 'a1'
},{
id: 'a12',
parent_id: 'a1'
},{
id: 'a13',
parent_id: 'a1'
},{
id: 'a2',
parent_id: 'a'
},{
id: 'a21',
parent_id: 'a2'
},{
id: 'a22',
parent_id: 'a2'
},{
id: 'a23',
parent_id: 'a2'
}];
data.forEach((e,i,a) => {var puid = makeUniqueId();
a.forEach(f => f.parent_id == e.id && (f.parent_id = puid));
e.id = puid;
});
document.write("<pre>" + JSON.stringify(data,null,2) + "</pre>");
每次运行代码时,您都会在
id
和parent_id
字段中获得不同的唯一值。如果您想让这个嵌套,那就完全不同了。关于javascript - 更改嵌套对象的父子相关ID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37262265/