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

Time:01-27

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});

CodePudding user response:

A quick one liner - You first flatten the results from the first map and then filter for items with href & name:

input.map(o => o.items).flat().filter(item => item.href && item.name)

CodePudding user response:

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; }

CodePudding user response:

const result = input.flatMap(obj => obj.items).filter(item => item.href)
  • Related