繁体   English   中英

Map 通过 Javascript 对象数组并返回一个满足条件的新对象

[英]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 返回一个对象数组,该数组仅包含具有namehref的元素,忽略不具有它的元素。

所以结果数组应该是这样的:

[
   { 
      "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()仅获取具有可用hrefname的元素

const result = input.flatMap(obj => obj.items).filter(({href, name}) => href && name)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM