我有一个看起来像这样的数组:
var a = [
{
value: 'Some data',
structure: 'linear',
id: 0,
children: [
{ id: 1, value: 'Some data', structure: undefined },
{ id: 2,
value: 'Some data',
structure: 'linear',
children: [
{ id: 4, value: 'Some data', structure: undefined }
]
}
]
},
{
id: 5,
structure: undefined
value: 'Some data',
},
];
我试图删除所有未定义结构值的对象。 每个不带子节点的匹配对象或子层次结构中的匹配项不应存在于输出数组中。 我不知道在运行时有多少级别的对象会有子数组
输出应该如下所示:
const output = [
{
value: 'Some data',
structure: 'linear',
id: 0,
children: [
{ id: 2, value: 'Some data', structure: 'linear' }
]
}
];
答案 0 :(得分:0)
递归地映射数据,然后在过滤未定义的值(如
)后返回结果
var a = [
{
value: 'Some data',
structure: 'linear',
id: 0,
children: [
{ id: 1, value: 'Some data', structure: undefined },
{
id: 2,
value: 'Some data',
structure: 'linear',
children: [
{ id: 4, value: 'Some data', structure: undefined }
]
}
]
},
{
id: 5,
structure: undefined,
value: 'Some data',
},
];
const getReducedArr = (data) => {
return data.map((obj) => {
if (obj.structure) {
const children = obj.children ? getReducedArr(obj.children) : [];
return {
...obj,
...(children.length > 0 ? { children } : undefined)
}
}
}).filter(data => data !== undefined)
}
const res = getReducedArr(a);
console.log(res)