3 回答
TA贡献1858条经验 获得超8个赞
您可以在原始数据数组上使用,该数组将返回对象及其 。映射对象中的 将是一个映射数组,再次使用相同的映射函数,如下所示:.map()idchildren
const data = [{ name: "Peter", age: "18", profession: "nurse", children: [] }, { name: "Jack", age: "98", profession: "doctor", children: [{ name: "Peter", age: "18", profession: "nurse", children: [] }, { name: "Varun", age: "80", profession: "scientist", children: [{ name: "Ishan", age: "62", profession: "teacher", children: [{ name: "Rahul", age: "23", profession: "engineer", children: [] }] }] } ] } ];
const res = data.map(function mapId({children, ...r}) {
return {...r, id: String(Math.random()), children: children.map(mapId)};
});
console.log(res);
TA贡献1963条经验 获得超6个赞
const obj = [{
name: "Jack",
age: "98",
profession: "doctor",
children: [
{
name: "Peter",
age: "18",
profession: "nurse",
children: [],
},
{
name: "Varun",
age: "80",
profession: "scientist",
children: [
{
name: "Ishan",
age: "62",
profession: "teacher",
children: [],
},
],
},
],
}];
const f = (_) => ({..._, id: String(Math.random()), children: _.children.map(f) })
console.log(obj.map(f));
TA贡献1828条经验 获得超3个赞
递归的一个很好的用例:
var data = [{
name : "Peter",
age : "18",
profession : "nurse",
children : []
},
{
name: "Jack",
age: "98" ,
profession: "doctor",
children: [ {
name : "Peter",
age : "18",
profession : "nurse",
children : []
},]
}
]
function addIdRecursively(data){
data.forEach(i=> {
i.id = String(Math.floor(Math.random()*10));
if(i.children.length>0){
addIdRecursively(i.children)
}
})
}
addIdRecursively(data);
console.log(data)
添加回答
举报