我正在尝试用一个随机的唯一ID值替换" ID“的每个实例。
有没有办法一次把它们全部替换掉?
My code:
var theobject = [
{
"id":"lol",
"milk":[
{
"id":"lol",
"waffle":[
{
"id":"lol",
"eggo":[]
}
]
},
{
"id":"lol",
"cookies":[]
}
]
},
{
"id":"lol",
"donut":[
{
"id":"lol",
"cheeto":[]
}
]
}
];
发布于 2018-06-09 04:16:18
尝试下面的方法,一个简单的递归解决方案,它将更新所有的id:
var theobject =[{"id":"lol","milk":[{"id":"lol","waffle":[{"id":"lol","eggo":[]}]},{"id":"lol","cookies":[]}]},{"id":"lol","donut":[{"id":"lol","cheeto":[]}]}];
function updateId(arr){
for(var i = 0; i < arr.length;i++){
Object.keys(arr[i]).forEach((key)=>{
if(arr[i][key].constructor.toString().indexOf("Array") > -1)
updateId(arr[i][key]);
});
if(arr[i].id)
arr[i].id = Math.random().toString(36).slice(-8);
}
}
updateId(theobject);
console.log(theobject);
发布于 2018-06-09 04:03:56
使用ramda
帮助修改对象,使用cuid
生成唯一ids:
const cuid = require('cuid')
const { evolve, map } = require('ramda')
const replaceIds = obj =>
evolve({
id: cuid,
children: map(replaceIds)
}, obj)
map(replaceIds, theobject) // usage
输出:
[
{
"id": "cji6e7qbf000cppatumn9nf6c",
"children": [
{
"id": "cji6e7qbf000dppatymupdw5r",
"children": [
{
"id": "cji6e7qbf000eppatbn3v7qlt",
"children": []
}
]
},
{
"id": "cji6e7qbf000fppat2ermw8jn",
"children": []
}
]
},
{
"id": "cji6e7qbf000gppatuxiv0bsh",
"children": [
{
"id": "cji6e7qbf000hppatx3em7n0e",
"children": []
}]
}
]
注意:这将按最初键入的方式回答您的问题。如果children
属性有所不同,但都是已知的,则可以按如下方式进行修改:
const replaceIds = obj =>
evolve({
id: cuid,
cheeto: map(replaceIds),
cookies: map(replaceIds),
donut: map(replaceIds),
eggo: map(replaceIds),
milk: map(replaceIds),
waffle: map(replaceIds),
}, obj)
如果它们不同并且未知,那么您需要尝试另一种方法。
发布于 2018-06-09 04:15:22
最简单的方法=递归解决方案。不需要库。
假设您知道每个对象都会有密钥的 id
& children
,下面的代码将会像发布的那样工作。
否则,如果对象上可能不存在键,则需要将每个突变范围嵌套在" if“大括号中。
const makeId = (objArray) => {
return objArray.map((obj, i) => {
obj.id = Math.floor(Math.random() * 1234567890); // Just making a simple ID. Typically use "uuid" or some other ID libarary generator.
if (obj.children.length) obj.children = makeId(obj.children);
return obj;
});
}
makeId(theobject);
备注此解决方案使用ES6。如果您需要使用Babel为ES6设置应用程序/algo的帮助,请查看我写的一篇here文章,该文章将指导您完成这一过程。
https://stackoverflow.com/questions/50767568
复制相似问题