Reputation: 6166
Having the following data structure:
[
{
"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": {}
}
]
}
]
It is needed a function that returns an array of objects which contains only the elements that have name
and href
, ignoring the ones that don't have it.
So the resulted array should be like this:
[
{
"name": "View Profile",
"href": "/profile"
},
{
"name": "Manage Account",
"href": "/manage"
},
{
"name": "Access",
"href": "/access"
},
{
"name": "Give Feedback",
"href": "/feedback"
}
]
I've tried to do it like this but without success:
const result = input.map(obj => obj.items).map(innerObj => innerObj.href ? ({innerObj.name, innerObj.href});
Upvotes: 0
Views: 936
Reputation: 444
Using a flatMap()
flattens the result by one level, next use the filter()
to get only elements with the href
and name
available
const result = input.flatMap(obj => obj.items).filter(({href, name}) => href && name)
Upvotes: 0
Reputation: 6255
A quick one liner - You flatten the results from the first map and then filter for items with href & name:
input.flatMap(({ items }) => items).filter(({ href, name }) => href && name)
Upvotes: 1
Reputation: 386560
You could check the properties and return either an object or an array for getting a flat result.
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; }
Upvotes: 0