简体   繁体   中英

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

I have an array of objects with this format:

[
    {
        "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"
    },
]

I want to map the array and return a new array with only specific parameters like "team_name" and "founded".

The new array should look like this:

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

Map the array?

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

according to your questing, let's assume, the initial array is 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"
},

]

now you want to remove some items from that array-objects,

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

more short hand answer:

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

now y is your new array.

if I understood the question wrong or you expect some other answer, please let me know by message or reply, will try best to solve it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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