【发布时间】:2018-03-15 20:19:20
【问题描述】:
给定这个结构,我如何在这个深度嵌套的对象结构中找到具有给定 id 的对象。
const menuItems = [
{
id: 1,
imageUrl: "http://placehold.it/65x65",
display: "Shop Women",
link: "#",
type: "image",
nextItems: [
{
id: 10,
display: "홈",
link: "#",
type: "menuitem"
},
{
id: 20,
display: "의류",
link: "#",
type: "menuitem-withmore",
nextItems: [
{
id: 100,
display: "I'm inside one nest",
link: "#",
type: "menuitem"
}
]
},
{
id: 30,
display: "가방",
link: "#",
type: "menuitem-withmore",
nextItems: []
},
{
id: 40,
display: "신발",
link: "#",
type: "menuitem-withmore",
nextItems: []
},
{
id: 50,
display: "악세서리",
link: "#",
type: "menuitem-withmore",
nextItems: []
},
{
id: 60,
display: "SALE",
link: "#",
type: "menuitem-withmore",
style: "bold",
nextItems: []
},
{
id: 70,
display: "브랜드",
link: "#",
type: "menuitem-withmore",
nextItems: []
},
{
type: "separator"
},
{
id: 80,
display: "위시리스트",
link: "#",
type: "menuitem"
},
{
id: 90,
display: "고객센터",
link: "#",
type: "menuitem"
},
{
id: 99,
display: "앱 다운로드",
link: "#",
type: "menuitem"
}
]
},
{
id: 2,
imageUrl: "http://placehold.it/65x65",
display: "Shop Men",
link: "#",
type: "image",
nextItems: [
{
id: 95,
display: "MEN's ITEMS.",
link: "#",
type: "menuitem"
}
]
}
];
假设我想用id: 20 找到对象并返回:
{
id: 20,
display: "의류",
link: "#",
type: "menuitem-withmore",
nextItems: [
{
id: 100,
display: "I'm inside one nest",
link: "#",
type: "menuitem"
}
]
},
我似乎找不到如何使用 lodash,并且有这个包可能已经解决了我的问题,但我不明白如何使它适用于我的用例。
【问题讨论】:
-
您要在
menuList或nextItems中查找该项目吗? -
正是我在退货示例中发布的内容。该对象以及它可能拥有的任何子对象,例如 nextItems。
-
@JoeLafiosca 不是骗子——他的问题和答案只涉及 1 级深度。
-
findAll 答案的深度超过 1 级,但无论如何都适用相同的迭代原则。如果您想推出自己的解决方案,您可以使用递归,如下面的 Kevin Qian 的 DFS 回答中所示。
标签: javascript object find lodash