Leo Messi
Leo Messi

Reputation: 6166

Map through a Javascript array of objects and return a new one satisfying a condition

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

Answers (3)

Solz
Solz

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

DannyMoshe
DannyMoshe

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

Nina Scholz
Nina Scholz

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

Related Questions