我有一个看起来像这样的对象数组:
var data = [
{
type: "parent",
children: [
{
type: "parent",
children: [
{
type: "parent"
},
{
type: "parent",
children: [
{
type: "notParent"
},
{
type: "parent"
}
]
}
]
}
]
},
{
type: "parent",
children: [
{
type: "parent"
}
]
},
{
type: "parent",
children: [
{
type: "parent",
children: [
{
type: "parent"
},
{
type: "parent"
}
]
},
{
type: "notParent"
}
]
},
{
type: "notParent"
}
]
这个数据是一个对象数组,可以有深度嵌套的对象。我想要做的是创建一个新数组,其中只包含类型为“parent”的对象并删除所有其他对象。我发现很难使这项工作适用于深层嵌套的对象。我尝试了以下多种变体:
var findAllParents = function(obj, type) {
if(obj.type === type) { return obj; }
for(var i in obj) {
if(obj.hasOwnProperty(i)){
var foundParents = findAllParents(obj[i], type);
if(foundParents) { return foundParents; }
}
}
return null;
};
我希望它返回这样的数据:
var data = [
{
type: "parent",
children: [
{
type: "parent",
children: [
{
type: "parent"
},
{
type: "parent",
children: [
{
type: "parent"
}
]
}
]
}
]
},
{
type: "parent",
children: [
{
type: "parent"
}
]
},
{
type: "parent",
children: [
{
type: "parent",
children: [
{
type: "parent"
},
{
type: "parent"
}
]
}
]
}
]
只返回所有类型为“parent”的对象
最佳答案
const data = [
{
type: "parent",
children: [
{
type: "parent",
children: [
{
type: "parent"
},
{
type: "parent",
children: [
{
type: "notParent",
children: [
{
type: "parent"
}
]
},
{
type: "parent"
}
]
}
]
}
]
},
{
type: "parent",
children: [
{
type: "parent"
}
]
},
{
type: "parent",
children: [
{
type: "parent",
children: [
{
type: "parent",
children: [
{
type: "parent",
children: [
{
type: "notParent"
}
]
}
]
},
{
type: "parent"
}
]
},
{
type: "notParent"
}
]
},
{
type: "notParent"
}
];
const filterCollectionItemsOfType = (collection, expectedType = 'parent') => {
const filteredCollection = collection.filter((item) => item.type === expectedType);
filteredCollection.forEach((item) => {
if (item.children && item.children.length) {
item.children = filterCollectionItemsOfType(item.children, expectedType);
}
});
return filteredCollection;
}
const parentsCollection = filterCollectionItemsOfType(data);
console.log(parentsCollection);
关于javascript - 过滤对象数组和嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56007638/