![](/img/trans.png)
[英]JavaScript how to map through two different arrays of objects and return one array conditionally
[英]Map through a Javascript array of objects and return a new one satisfying a condition
具有以下數據結構:
[
{
"items": [
{
"name": "View Profile",
"href": "/profile",
"icon": {}
},
{
"name": "Manage Account",
"href": "/manage",
"icon": {}
},
{
"name": "Other",
"icon": {}
}
]
},
{
"items": [
{
"name": "Access",
"href": "/access",
},
{
"name": "Give Feedback",
"href": "/feedback",
"icon": {}
}
]
}
]
需要一個 function 返回一個對象數組,該數組僅包含具有name
和href
的元素,忽略不具有它的元素。
所以結果數組應該是這樣的:
[
{
"name": "View Profile",
"href": "/profile"
},
{
"name": "Manage Account",
"href": "/manage"
},
{
"name": "Access",
"href": "/access"
},
{
"name": "Give Feedback",
"href": "/feedback"
}
]
我試過這樣做但沒有成功:
const result = input.map(obj => obj.items).map(innerObj => innerObj.href ? ({innerObj.name, innerObj.href});
一個快速的班輪 - 您將第一個 map 的結果展平,然后過濾具有 href 和名稱的項目:
input.flatMap(({ items }) => items).filter(({ href, name }) => href && name)
您可以檢查屬性並返回 object 或數組以獲得平面結果。
const data = [{ items: [{ name: "View Profile", href: "/profile", icon: {} }, { name: "Manage Account", href: "/manage", icon: {} }, { name: "Other", icon: {} }] }, { items: [{ name: "Access", href: "/access" }, { name: "Give Feedback", href: "/feedback", icon: {} }] }], result = data.flatMap(({ items }) => items.flatMap(({ name, href }) => name && href? { name, href }: []) ); console.log(result);
.as-console-wrapper { max-height: 100%;important: top; 0; }
使用flatMap()
將結果展平一級,接下來使用filter()
僅獲取具有可用href
和name
的元素
const result = input.flatMap(obj => obj.items).filter(({href, name}) => href && name)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.