繁体   English   中英

我如何 map 对象数组并从对象返回特定属性

[英]How can i map array of objects and return specific properties from the objects

我有一个具有这种格式的对象数组:

[
    {
        "team_key": "2611",
        "team_name": "Leicester",
        "team_badge": "https://apiv2.apifootball.com/badges/2611_leicester.png",
        "founded": "1884; 136 years ago (as Leicester Fosse FC)",
        "city": "Leicester"
    },
    {
        "team_key": "2612",
        "team_name": "Everton",
        "team_badge": "https://apiv2.apifootball.com/badges/2612_everton.png",
        "founded": "1878; 142 years ago",
        "city": "Liverpool"
    },
]

我想 map 数组并返回一个新数组,其中只有特定参数,如“team_name”和“founded”。

新数组应如下所示:

 [
        {
            "team_name": "Leicester",
            "founded": "1884; 136 years ago (as Leicester Fosse FC)",
        },
        {
            "team_name": "Everton",
            "founded": "1878; 142 years ago",
        }
    ]

Map 阵列?

 const data = [ { "team_key": "2611", "team_name": "Leicester", "team_badge": "https://apiv2.apifootball.com/badges/2611_leicester.png", "founded": "1884; 136 years ago (as Leicester Fosse FC)", "city": "Leicester" }, { "team_key": "2612", "team_name": "Everton", "team_badge": "https://apiv2.apifootball.com/badges/2612_everton.png", "founded": "1878; 142 years ago", "city": "Liverpool" }, ] console.log( // Destruct the object argument into desired keys // and return a new object from them. data.map(({ team_key, founded }) => ({ team_key, founded })) )

根据您的要求,我们假设初始数组是 x。

x = [
{
    "team_key": "2611",
    "team_name": "Leicester",
    "team_badge": "https://apiv2.apifootball.com/badges/2611_leicester.png",
    "founded": "1884; 136 years ago (as Leicester Fosse FC)",
    "city": "Leicester"
},
{
    "team_key": "2612",
    "team_name": "Everton",
    "team_badge": "https://apiv2.apifootball.com/badges/2612_everton.png",
    "founded": "1878; 142 years ago",
    "city": "Liverpool"
},

]

现在您想从该数组对象中删除一些项目,

y = x.map ( v => {
    return {
        team_name: v.team_name,
        founded: v.founded
    }
})

更简短的答案:

y =  x.map(({ team_key, founded }) => ({ team_key, founded }))

现在 y 是你的新数组。

如果我对问题的理解有误或您希望得到其他答案,请通过消息或回复告诉我,我们会尽力解决。

暂无
暂无

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

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