Сравнение заданной строки с вложенным свойством массива - PullRequest
0 голосов
/ 29 мая 2020

Я создаю массив players, который будет добавлен, если solver не найден в свойствах name внутри players

let players = []

let solver = 'Any Name Given'

// This if statement is the issue : How to check the name properties and compare to solver 
// If the solver's name is already in players : add +1 point
if(players.includes(solver)){

   // Give The Player +1 point

   return console.log('Player Exists')

 } else {

   // Add The newPlayer to players with a starting point 
   let newPlayer = [name = solver, points = 1]
   players.push(newPlayer)

}

Как сравнить solver внутри name из players. Я пробовал players[name] и players.name безуспешно

1 Ответ

1 голос
/ 29 мая 2020

В вашем else вы должны иметь:

const newPlayer = {name: solver, points: 1};

т.е. объект, а не массив. Итак, у вас есть массив players, который всегда будет иметь player объектов

Теперь, поскольку у вас есть массив объектов, вам нужно использовать что-то вроде some , чтобы узнать, объект, соответствующий вашему условию, существует или нет:

Условие if можно заменить на:

if (players.some(player => player.name === solver))

Я только что видел, что вы хотите увеличить очки найденного игрока на 1. В этом случае вы должны использовать find вместо some, чтобы вы могли получить доступ к найденному игроку и обновить его свойство points. Так что сделайте это:

const player = players.find(player => player.name === solver);

if (player) {
    player.points++;
} else {
    const newPlayer = {name: solver, points: 1};
    players.push(newPlayer)
}

...