Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update and add data to JSON

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{"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}]}]

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading