假设我们有一个包含父对象和其相关子对象数组的对象数组。以下是一种在JavaScript中遍历该数组并为每个子对象数组分配父对象的示例方法。
// 假设有以下对象数组
const objects = [
{
id: 1,
name: 'Parent 1',
children: [
{ id: 1, name: 'Child 1' },
{ id: 2, name: 'Child 2' }
]
},
{
id: 2,
name: 'Parent 2',
children: [
{ id: 3, name: 'Child 3' },
{ id: 4, name: 'Child 4' }
]
}
];
// 遍历对象数组
for (let i = 0; i < objects.length; i++) {
const parent = objects[i];
// 为每个子对象数组分配父对象
for (let j = 0; j < parent.children.length; j++) {
parent.children[j].parent = parent;
}
}
// 现在,每个子对象都有一个"parent"属性,指向其父对象
console.log(objects);
执行代码后,输出的结果如下:
[
{
"id": 1,
"name": "Parent 1",
"children": [
{
"id": 1,
"name": "Child 1",
"parent": {
"id": 1,
"name": "Parent 1",
"children": [
{
"id": 1,
"name": "Child 1",
"parent": { ... }
},
{ ... }
]
}
},
{ ... }
]
},
{ ... }
]
注意:这种方法会将"parent"属性直接添加到每个子对象中,因此您可能需要在生产代码中进行更好的错误处理。