Home > Back-end >  Update and add data to JSON
Update and add data to JSON

Time:10-29

I have this JSON in separate file. Am currently using this:

[{"username":"John","id":"1","points":[{"type":"gold","amount":1}]},
{"username":"Mark","id":"2","points":[{"type":"bronze","amount":13}]},
{"username":"Mayou","id":"3","points":[{"type":"silver","amount":10}]}]
let username = "John";
let id = 1;
let amount = 1;
let type = silver;

const configDirectory = path.resolve(process.cwd(), "essentials");

let tableSend = JSON.parse(readFileSync(path.join(configDirectory, '../essentials/tableSend.json')));
const exist = tableSend.filter(item => item.id == id).length > 0;
if (exist == true) {

} else {
  const values = {
    username: username,
    id: id,
    points: [{
      type: type,
      amount: amount
    }]
  }
  tableSend.push(values);
  let newData = JSON.stringify(tableSend);
  writeFileSync(path.join(configDirectory, '../essentials/tableSend.json'), newData);
}

How can i achieve updating of data or writting a new data into JSON? So results would be this:

[{"username":"John","id":"1","points":[{"type":"gold","amount":1},{"type":"silver", "amount":1}]},
{"username":"Mark","id":"2","points":[{"type":"bronze","amount":13}]},
{"username":"Mayou","id":"3","points":[{"type":"silver","amount":10}]}]

OR counting them more?

[{"username":"John","id":"1","points":[{"type":"gold","amount":50}]},
{"username":"Mark","id":"2","points":[{"type":"bronze","amount":13}]},
{"username":"Mayou","id":"3","points":[{"type":"silver","amount":10}]}]

CodePudding user response:

Use tableSend.find() to find the object with id:1 and push onto its points array. If not found, you add the new user to the array as you're doing.

const exist = tableSend.find(item => item.id == id);
if (exist) {
  exist.points.push({
    type: type,
    amount: amount
  });
} else {
  const values = {
    username: username,
    id: id,
    points: [{
      type: type,
      amount: amount
    }]
  }
  tableSend.push(values);
}
let newData = JSON.stringify(tableSend);
writeFileSync(path.join(configDirectory, '../essentials/tableSend.json'), newData);
  • Related