Как я могу сопоставить массив объектов и вернуть определенные c свойства из объектов - PullRequest
0 голосов
/ 04 августа 2020

У меня есть массив объектов в этом формате:

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

Я хочу сопоставить массив и вернуть новый массив только с указанными c параметрами, такими как «team_name» и «found».

Новый массив должен выглядеть так:

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

Ответы [ 2 ]

1 голос
/ 04 августа 2020

Сопоставить массив?

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

)
0 голосов
/ 04 августа 2020

в соответствии с вашим запросом, допустим, исходный массив равен 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 - ваш новый массив.

если я неправильно понял вопрос или вы ожидаете другого ответа, дайте мне знать сообщение или ответ, постараемся решить эту проблему.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...