Как из массива с обьектами получить в консоле обьекты с определенными ключами

function getGoalsStat(players) {
return playersCopy
}

const players = [
{
name: 'Jason Mount',
birthdate: '19.12.1993',
country: 'Deutschland',
number: '21',
team: 'Manchester United',
position: 'MF',
goals: 4,
},
{
name: 'Jason Mount',
birthdate: '01.01.2001',
country: 'Deutschland',
number: '16',
team: 'Manchester United',
position: 'MF',
goals: 0,
}]
console.log(getGoalsStat(players))

Должен в консоле получить

[{ name: 'Jason Mount', team: 'Manchester United', goals: 4 },
{ name: 'Jason Mount, team: 'Manchester United', goals: 0 }]

Ответы (1 шт):

Автор решения: ya_ilya
// keys -> ключи которые вам нужны
function getGoalsStat(playersArray, keys = [ 'name', 'team', 'goals' ]) {
  return playersArray.map(it => {
    let object = {};

    for (const key in it) {
      if (keys.includes(key)) {
        object[key] = it[key]
      }
    }

    return object
  })
}

const players = [
  {
    name: 'Jason Mount',
    birthdate: '19.12.1993',
    country: 'Deutschland',
    number: '21',
    team: 'Manchester United',
    position: 'MF',
    goals: 4,
  },
  {
    name: 'Jason Mount',
    birthdate: '01.01.2001',
    country: 'Deutschland',
    number: '16',
    team: 'Manchester United',
    position: 'MF',
    goals: 0,
  }
]

console.log(getGoalsStat(players))

Вывод:

[ { name: 'Jason Mount', team: 'Manchester United', goals: 4 },
  { name: 'Jason Mount', team: 'Manchester United', goals: 0 } ]
→ Ссылка