如何在对象中迭代嵌套对象



我有一个数组,如下所示:

const arr = [
{
parent: 'A',
children: ['B'],
},
{
parent: 'B',
children: ['C'],
},
{
parent: 'C',
children: ['D']
}];

我想创建一个函数,它将使用这个数组并产生以下对象:

const result = {
parent: 'A',
children: [{
parent: 'B',
children: [{
parent: 'C',
children: [{
parent: 'D',
children: []
}]
}]
}]
};

因此结果类型看起来像:

type Result = {
parent: string;
children: Result[];
};

到目前为止我尝试过的:

type TInput = {
parent: string;
children: string[];
};
type Result = {
parent: string;
children: Result[];
};
// can assume we know initial parent is 'A'
const fn = (parent: string, inputArr: TInput[]) => {
const result: TResult[] = [];
let newParent: string[] = [];
while (newParent.length !== 0) {
const index = inputArr.findIndex(
(input) => input.parent === parent
);
result.push({
parent: inputArr[index].parent,
children: [], // need to populate on next pass?
});
newParent = inputArr[index].children;
}
return result;
};

我不知道输入数组中有多少个对象,但可以假设第一个对象是已知的初始父/子对象(示例中为"A")。非常感谢您的帮助。感谢

我会使用父映射将子属性重新创建为父对象的数组:

const arr = [
{
parent: 'A',
children: ['B'],
},
{
parent: 'B',
children: ['C'],
},
{
parent: 'C',
children: ['D']
},
{
parent: 'D',
children: []
}
];
const makeTree = (manyParents,rootName) => {
// copy parent objects into a map.
let mapIt = new Map(manyParents.map(pObject => {
return [pObject.parent, pObject];
}));

// recreate children arrays for each parents.
mapIt.forEach((oneParent) => {
let newChildrenArray = [];
//find every children objects.
oneParent.children.forEach((oneChild) => {
newChildrenArray.push(mapIt.get(oneChild));
});
//replace children array.
oneParent.children = newChildrenArray;
});
return mapIt.get(rootName);
}
let tree = makeTree(arr,'A');
console.log(tree)

您可以使用Array#reverseArray#reduce方法,如下所示:

const 
arr = [ { parent: 'A', children: ['B'], }, { parent: 'B', children: ['C'], }, { parent: 'C', children: ['D'] }],
output = arr.reverse().reduce(
(acc,{parent,children}) =>
!acc.parent ? 
({parent,children:children.map( ([parent]) => ({parent,children:[]}) )}):
({parent,children:[acc]}),{}
);

console.log( output );

这似乎完成了任务:

这是ts版本:

// here i just copy your data
const data = [{
parent: 'A',
children: ['B'],
},
{
parent: 'C',
children: ['D']
},
{
parent: 'B',
children: ['C'],
}
];
const expectedResult = {
parent: 'A',
children: [{
parent: 'B',
children: [{
parent: 'C',
children: [{
parent: 'D',
children: []
}]
}]
}]
};
type TInput = {
parent: string;
children: string[];
};
type TResult = {
parent: string;
children: TResult[];
};

// there is the function that takes an input (the parent element) and an array (all the children)
const parseArray = (obj: TInput, arr: TInput[]): TResult => {
return {
parent: obj.parent,
// if the children exists on the array, we use it, else we create an empty one, which will be used to recusivly generate the tree
children: obj.children.map(child => data.find(e => e.parent === child) ?? {
parent: child,
children: []
}).map(e => parseArray(e, arr))
}
}
// we get the root obj (as you said the first el)
const root = data.shift()!
// and we call the function
console.log(parseArray(root, data))
// we verify that the objects are the same using json (directly using == on objects compares their locations on the disk)
console.log(JSON.stringify(parseArray(root, data)) === JSON.stringify(expectedResult))

这是片段(我们不能直接在片段上运行ts):

// here i just copy your data
const data = [{
parent: 'A',
children: ['B'],
},
{
parent: 'C',
children: ['D']
},
{
parent: 'B',
children: ['C'],
}
];
const expectedResult = {
parent: 'A',
children: [{
parent: 'B',
children: [{
parent: 'C',
children: [{
parent: 'D',
children: []
}]
}]
}]
};
// there is the function that takes an input (the parent element) and an array (all the children)
const parseArray = (obj, arr) => {
return {
parent: obj.parent,
// if the children exists on the array, we use it, else we create an empty one, which will be used to recusivly generate the tree
children: obj.children.map(child => data.find(e => e.parent === child) ?? {
parent: child,
children: []
}).map(e => parseArray(e, arr))
}
}
// we get the root obj (as you said the first el)
const root = data.shift()
// and we call the function
console.log(parseArray(root, data))
// we verify that the objects are the same using json (directly using == on objects compares their locations on the disk)
console.log(JSON.stringify(parseArray(root, data)) === JSON.stringify(expectedResult))

最新更新