【发布时间】:2020-05-23 11:06:27
【问题描述】:
我有这样的变量 rawData:
let rawData = [
{
title: '1',
result: '1',
child: [
{
title: '1-1',
result: '1-1',
child: [
{
title: '1-1-1',
result: '1-1-1',
child: [
{
title: '1-1-1-1',
result: '1-1-1-1',
child: [
{
title: '1-1-1-1-1',
result: '1-1-1-1-1',
},
],
},
{
title: '1-1-1-2',
result: '1-1-1-2',
},
{
title: '1-1-1-3',
result: '1-1-1-3',
},
],
},
],
},
],
},
];
和我的功能。它按预期运行,这是我的功能:
let normalizeArray = [];
function test(array) {
for (const key in array) {
if (array.hasOwnProperty(key)) {
const element = array[key];
if (element.hasOwnProperty('child')) {
test(element.child);
delete element.child;
normalizeArray.unshift(Object.assign({}, element));
} else {
normalizeArray.push(Object.assign({}, element));
}
}
}
}
并返回(预期):
[
{ title: '1', result: '1' },
{ title: '1-1', result: '1-1' },
{ title: '1-1-1', result: '1-1-1' },
{ title: '1-1-1-1', result: '1-1-1-1' },
{ title: '1-1-1-1-1', result: '1-1-1-1-1' },
{ title: '1-1-1-2', result: '1-1-1-2' },
{ title: '1-1-1-3', result: '1-1-1-3' },
];
但是,如果 rawData 是这样的:
let rawData = [
{
title: '1',
result: '1',
child: [
{
title: '1-1',
result: '1-1',
child: [
{
title: '1-1-1',
result: '1-1-1',
child: [
{
title: '1-1-1-1',
result: '1-1-1-1',
child: [
{
title: '1-1-1-1-1',
result: '1-1-1-1-1',
},
],
},
{
title: '1-1-1-2',
result: '1-1-1-2',
},
{
title: '1-1-1-3',
result: '1-1-1-3',
},
],
},
],
},
],
},
{
title: '2',
result: '2',
child: [
{
title: '2-2',
result: '2-2',
},
],
},
{
title: '3',
result: '3',
},
];
使用我的函数,它返回:
[
{ title: '2', result: '2' },
{ title: '1', result: '1' },
{ title: '1-1', result: '1-1' },
{ title: '1-1-1', result: '1-1-1' },
{ title: '1-1-1-1', result: '1-1-1-1' },
{ title: '1-1-1-1-1', result: '1-1-1-1-1' },
{ title: '1-1-1-2', result: '1-1-1-2' },
{ title: '1-1-1-3', result: '1-1-1-3' },
{ title: '2-2', result: '2-2' },
{ title: '3', result: '3' },
];
我怎么能得到这样的结果:
[
{ title: '1', result: '1' },
{ title: '1-1', result: '1-1' },
{ title: '1-1-1', result: '1-1-1' },
{ title: '1-1-1-1', result: '1-1-1-1' },
{ title: '1-1-1-1-1', result: '1-1-1-1-1' },
{ title: '1-1-1-2', result: '1-1-1-2' },
{ title: '1-1-1-3', result: '1-1-1-3' },
{ title: '2', result: '2' },
{ title: '2-2', result: '2-2' },
{ title: '3', result: '3' },
];
如果您能帮助我编写更精简的代码,请随时帮助我。我还是 javascript 新手
【问题讨论】:
-
之后使用合适的
sort()怎么样?可能还会稍微简化您的其他功能。 -
嗯?虚拟数据实际上是字符串:比如标题:“爱丽丝梦游仙境”,结果:“好”,这个数字只是为了让它更清楚......或者我错过了什么?
标签: javascript arrays object recursion