使用以下示例数据,我试图删除数组children
为空的对象条目。
因此,根据下面的allData
,将单独删除以下内容:
{
"name": "Tom",
"info": "Tom info",
"section_id": 3,
"children": []
}
由于"children": []
为空。
我尝试了以下方法,但不确定如何达到预期的结果并针对特定的对象条目。
根据下面的注释,需要递归解决方案,但我不确定如何做到这一点。
let allData = {
"name": "Max",
"info": "Max info",
"section_id": 1,
"children": [
{
"childName": "Sam",
"childAge": 5
},
{
"name": "Helen",
"info": "Helen info",
"section_id": 2,
"children": [
{
"childName": "Sarah",
"childAge": 11
},
{
"name": "Tom",
"info": "Tom info",
"section_id": 3,
"children": []
}
]
}
]
}
let children = allData.children
const myData = children.filter(v => !v.children || v.children.length > 0)
myData.forEach((element, index) => {
if (element) {
console.log(element)
}
});
生成以下控制台日志:
{
"childName": 'Sam',
"childAge": 5
}
{
"name": "Helen",
"info": "Helen info",
"section_id": 2,
"children": [
{
"childName": "Sarah",
"childAge": 11
},
{
"name": "Tom",
"info": "Tom info",
"section_id": 3,
"children": []
}
]
}
我正在考虑使用index
拼接数组以删除:
{
"name": "Tom",
"info": "Tom info",
"section_id": 3,
"children": []
}
请帮忙就太好了。
const data = {"name":"Max","info":"Max info","section_id":1,"children":[{"childName":"Sam","childAge":5},{"name":"Helen","info":"Helen info","section_id":2,"children":[{"childName":"Sarah","childAge":11},{"name":"Tom","info":"Tom info","section_id":3,"children":[]}]}]}
let a = [[data, null, 0]] // array of [item, parent, index]
// top level has null parent
while(a.length) {
let [item, parent, index] = a.pop()
if(item.children) {
if(item.children.length)
item.children.forEach((child,index)=>a.push([child, item, index]))
else
parent.children.splice(index, 1)
}
}
console.log(data)