我有一个看起来像这样的对象数组:
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”的所有对象
答案 0 :(得分:1)
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);
答案 1 :(得分:0)
您可以复制data
,然后应用递归函数,该函数将使用children
filter()
数组中删除所需的元素
var data = [ { type: "parent", children: [ { type: "parent", children: [ { type: "parent" }, { type: "parent" } ] } ] }, { type: "parent", children: [ { type: "parent" } ] }, { type: "parent", children: [ { type: "parent", children: [ { type: "parent" }, { type: "parent" } ] }, { type: "notParent" } ] } ]
function remove(obj){
if(obj.children){
obj.children = obj.children.filter(x => x.type === "parent");
obj.children.forEach(x => remove(x))
}
}
let copy = JSON.parse(JSON.stringify(data));
copy.forEach(x => remove(x));
console.log(copy)