简体   繁体   English

迭代对象中的所有属性,查找并替换

[英]Iterate all the property in object, find and replace

I have this Javascript object generated from my code and player object is 我有从代码生成的Javascript对象,播放器对象是

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? 我的问题是如何遍历播放器对象中的所有卡并将所有“ A” faceValue替换为1? Using findIndex or splice? 使用findIndex还是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

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 更新:如果我们不生成新值,最好使用forEach

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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