如何编辑“ bal”的值

时间:2019-07-03 14:43:13

标签: javascript node.js json database

我正在尝试使用JavaScript中的.json创建一个简单的数据库。如何编辑“ player1”的“ bal”值?

{
"player": [{
    "number": "1122", 
    "name": "player1",
    "bal": 0,     //How to change this 0 into 100?
    "role": "Owner of the MoS Game",
    "rank": "Normal"
}, {
    "DCNumber": "3344", 
    "name": "player2",
    "bal": 0,
    "role": "Helper",
    "rank": "Normal"
}, {
    "DCNumber": "5566",
    "name": "player3",
    "bal": 0,
    "role": "Player",
    "rank": "Normal"
}],

"rankCatagory": ["Normal", "Bronze", "Silver", "Gold", "Platinum", "VIP", "VIP+", "MVP", "MVP+", "MVP++"]
}
const fs = require('fs');
var rawdata = fs.readFileSync('Data.json');
var data = JSON.parse(rawdata);
console.log(data);
console.log("Successfully Loaded \"Data.json\"");

/*

What should I do to edit the value of bal?

*/

2 个答案:

答案 0 :(得分:0)

data.player.find(p=>p.name=="player1").bal = 100;

或者如果它始终是第一个,则不用.find(...)代替[0]

答案 1 :(得分:0)

如果要为每个玩家更改它:

data["player"] = data["player"].map(el => {
    return {
        ...el,
        bal: 100    
    }
})

否则,您应该知道名称:

const name = "player1"
data["player"] = data["player"].map(el => {
    if(el.name = name){
        return {
            ...el,
            bal: 100    
        }
    } else {
      return {
            ...el,
        }
     }
})