0

I have this Javascript object generated from my code and player object is

const player = {
   cards: []
}

My question is how do I loop through all my card in player object and replace all the "A" faceValue to 1? Using findIndex or splice?

player: Object
cards: Array(2)
0: Array(1)
0: card {suit: "spades", face: "7", faceValue: 7}
length: 1
__proto__: Array(0)
1: Array(1)
0: card {suit: "clubs", face: "A", faceValue: 11}
length: 1
1: Array(2)
0: card {suit: "spades", face: "A, faceValue: 11}
length: 1
3
  • write a loop, check if face is == A, if it is, set faceValue to 1 Commented May 2, 2019 at 23:58
  • 1
    It's unclear what the structure of your data is (from the log output), so it's difficult to suggest a way to iterate over that structure. Commented May 2, 2019 at 23:58
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented May 2, 2019 at 23:58

1 Answer 1

1

You can use Array map your cards object to update its value

player.cards = player.cards.map(card => {
    if (card.face === 'A') card.faceValue = 1;
    return card;
});

Update: It is better to use forEach if we are not generating new values

player.cards.forEach(card => {
    if (card.face === 'A') card.faceValue = 1;
});
Sign up to request clarification or add additional context in comments.

3 Comments

No need to use .map if you mutate the objects (i.e. not generating new values). Just use .forEach then.
any example of .forEach to find and replace?
yes @FelixKling is right but mutating arrays is mostly a bad practice. I'd create a new one like const myCards = player.cards.map(....) and if needed assign that array to the player afterwards. Imho this is a better pattern, even if it may be slower

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.