让我先给你看代码,然后我会解释我的需求。我想向您展示输入数组的结构和期望的结果:
[
{
link: "someurl",
name: "Foo",
subCats: [
{
link: "anotherurl",
name: "Bar",
subCats: [
{
link: "anotherurl",
subCats: [
{
link: "onemorekink"
name: "Prod",
}
]
}
]
},
{
link: "someurll",
name: "Fuzzy",
subCats: [
{
link: "besturiever",
name: "SomeName",
subCats: [
{
link: "onemore",
name: "Aloc",
subCats: [
{
link: "anotherlink"
name: "Final",
}
]
}
]
}
]
}
]
}
]
我需要在结果中得到什么:
{
link: "onemorekink"
name: "Prod",
},
{
link: "anotherlink"
name: "Final",
}
希望您能理解。基本上我需要以某种方式获取不包含子 subCats
的最后一个 subCats
元素并将其附加到结果数组。
我尝试使用 Lodash,因为它非常适合数组/对象操作。提前感谢您的帮助。
最佳答案
试试这个
let b=[]; // result here
let f = x => x.map( y=> y.subCats ? f(y.subCats) : b.push(y) );
f(a);
let a = [
{
link: "someurl",
name: "Foo",
subCats: [
{
link: "anotherurl",
name: "Bar",
subCats: [
{
link: "anotherurl",
subCats: [
{
link: "onemorekink",
name: "Prod",
}
]
}
]
},
{
link: "someurll",
name: "Fuzzy",
subCats: [
{
link: "besturiever",
name: "SomeName",
subCats: [
{
link: "onemore",
name: "Aloc",
subCats: [
{
link: "anotherlink",
name: "Final",
}
]
}
]
}
]
}
]
}
];
let b=[];
let f = x => x.map( y=> y.subCats ? f(y.subCats) : b.push(y) );
f(a);
console.log(b);
关于javascript - Lodash 从混合数组和对象中获取叶子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54149523/