'How can I update specific index JSON data using contact form in Node.js

I have a 3 files one is index.ejs file where I have designed form and I want to update specific json index data with my new data using this html form (index.ejs)

index.ejs

<% if(prodata){ %>
    <h2>Edit Entry Form</h2>
    <form action="/update" method="post">
      
      <input type="hidden" name="id" value="<%= prodata.id %>">
      <input type="text" name="studentName" placeholder="student name" value="<%= prodata.studentName %>">
      <input type="number" name="maths" placeholder="maths" value="<%= prodata.maths %>">
      <input type="number" name="physics" placeholder="physics" value="<%= prodata.physics %>">
      <input type="number" name="chemistry" placeholder="chemistry" value="<%= prodata.chemistry %>">
      <input type="number" name="bio" placeholder="bio" value="<%= prodata.bio %>">
      <input type="number" name="computer" placeholder="computer" value="<%= prodata.computer %>">
      <input type="submit">
    </form>
    <% } %>

Here is the index.js file where I have wrote all my node.js logics where I have set /update POST method which is coming from index.ejs form, and I will get all the form data in req.body and I want to update that data to the JSON file at specific index.

index.js

var express = require('express');
const { append } = require('express/lib/response');
var router = express.Router();
var fs = require('fs');
var details = fs.readFileSync('./data.json', 'utf-8');
var jdata = JSON.parse(details);

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', {jdata, prodata: ""});
});

router.post('/update', function(req, res, next) {
  let id =  req.body.id;
  jdata[id].studentName = req.body.studentName;
  jdata[id].maths = req.body.maths*1;
  jdata[id].physics = req.body.physics*1;
  jdata[id].chemistry = req.body.chemistry*1;
  jdata[id].bio = req.body.bio*1;
  jdata[id].computer = req.body.computer*1;

  fs.writeFileSync('./data.json', JSON.stringify(jdata), 'utf-8')
  res.render('index', {jdata});
  res.redirect('/')
});

module.exports = router;

Here is the data.json file where already some datas are there, and I want to update specific index data with update from data.

data.json

[
{
    'id': 1
    'studentName': 'John', 
    'maths': 50,
    'physics': 95,
    'chemistry': 84, 
    'bio': 84,
    'computer': 75
},
{
    'id': 2
    'studentName': 'Samuel', 
    'maths': 40,
    'physics': 90,
    'chemistry': 84, 
    'bio': 84,
    'computer': 85
},
{
    'id': 3
    'studentName': 'Tomy', 
    'maths': 90,
    'physics': 45,
    'chemistry': 34, 
    'bio': 84,
    'computer': 95
},

]



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source