如何更改JSON文件中的变量?

时间:2016-06-20 19:11:29

标签: javascript json

我需要更改json文件中的state, 我必须在我的json中使用HTML和javascript进行游戏,我的玩家拥有名称,密码和状态等属性。

我的请求只需要查看state个数字,并在必要时进行更改。

如何编写仅更改player.state的代码,从1到3?

这是JSON文件

[
    {"pseudo":"player1","password":"player","state":"1"},
    {"pseudo":"player2","password":"player","state":"0"}
]

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:



function changeState(playersArray,playerToChange,newState){
     playersArray.find(function(player) {return player.pseudo == playerToChange}).state = newState;
}

var players = [
    {"pseudo":"player1","password":"player","state":"1"},
    {"pseudo":"player2","password":"player","state":"0"}
]

changeState(players,"player2",3);