筛选数组以返回深层对象



我有一个像下面这样的深层次数组,

const cat = [
{
name: "cat 1",
id: 1,
subCat: [
{
name: "sub 1",
id: 10,
subSubCat: [
{ summary: "summary1", id: 20 },
{ summary: "summary2", id: 21 },
],
},
],
},
{
name: "cat 2",
id: 2,
subCat: [
{
name: "sub 2",
id: 20,
subSubCat: [
{ summary: "summary1", id: 30 },
{ summary: "summary2", id: 31 },
],
},
],
},
];

我必须过滤subSubCat id(31),它应该返回一个汇总值(summary2)。

可以使用Array。map和Array。flat获取subSubCat列表,然后使用Array。find按id查找subSubCat项。

const cat = [
{
name: "cat 1",
id: 1,
subCat: [
{
name: "sub 1",
id: 10,
subSubCat: [
{ summary: "summary1", id: 20 },
{ summary: "summary2", id: 21 },
],
},
],
},
{
name: "cat 2",
id: 2,
subCat: [
{
name: "sub 2",
id: 20,
subSubCat: [
{ summary: "summary1", id: 30 },
{ summary: "summary2", id: 31 },
],
},
],
},
];
var subSubCats = cat.map(item => item.subCat.map(subCatItem => subCatItem.subSubCat)).flat(2);
var result = subSubCats.find(e => e.id == 31);
console.log(result.summary);

这看起来像是需要两级循环和find()的东西。

const cat = [
{
name: "cat 1",
id: 1,
subCat: [
{
name: "sub 1",
id: 10,
subSubCat: [
{ summary: "summary1", id: 20 },
{ summary: "summary2", id: 21 },
],
},
],
},
{
name: "cat 2",
id: 2,
subCat: [
{
name: "sub 2",
id: 20,
subSubCat: [
{ summary: "summary1", id: 30 },
{ summary: "summary2", id: 31 },
],
},
],
},
];

for(let i =0 ; i < cat.length;i++){
if(Array.isArray(cat[i].subCat)){
let subCatArray = cat[i].subCat;
//console.log(subCatArray);
for(let j =0 ; j < subCatArray.length;j++){
let subSubArray = subCatArray[j].subSubCat;
if(Array.isArray(subSubArray)){
//console.log(subSubArray);
let foundObject = subSubArray.find((x) => 
x.id === 31
);
//console.log(foundObject);
if(foundObject!==undefined) 
{
console.log(foundObject.summary);
break;
}
}
}
}
}

相关内容

  • 没有找到相关文章

最新更新