skip to Main Content

I have an object that looks like this :

{
  "mark": [
    {
     "id":1,
    "name": "mark",
      "age":26
    },
    {
       "id":2,
     "name": "mark",
      "age":25
    }
],
"jack": [
    {
        "id":1,
      "name": "jack",
      "age":26
     
    },
    {
        "id":2,
      "name": "jack",
      "age": 24,
      
    }
  ]
}

WHAT I GOT AS OUTPUT IF A NEW USER IS ADDED IT IS NOT APPENDED, BUT IT IS OVERWRITTEN OR CREATED AS A NEW OBJECT

{
     "mark": [
            {
             "id":1,
            "name": "mark",
              "age":26
            },
            {
               "id":2,
             "name": "mark",
              "age":25
            }
        ],
        "jack": [
            {
                "id":1,
              "name": "jack",
              "age":26
             
            },
            {
                "id":2,
              "name": "jack",
              "age": 24,
              
            }
          ],
 
        }   "Josh": [ 
            {
                "id":1,
              "name": "Josh",
              "age":26
             
            },
            {
                "id":2,
              "name": "Josh",
              "age": 24,
              
            }
          ]

Expected

if new person data arrives in my JSON File, that should be appended to the next array with key values of array of Objects,

like

     {
          "mark": [
            {
             "id":1,
            "name": "mark",
              "age":26
            },
            {
               "id":2,
             "name": "mark",
              "age":25
            }
        ],
        "jack": [
            {
                "id":1,
              "name": "jack",
              "age":26
             
            },
            {
                "id":2,
              "name": "jack",
              "age": 24,
              
            }
          ],
"Josh": [ 
            {
                "id":1,
              "name": "Josh",
              "age":26
             
            },
            {
                "id":2,
              "name": "Josh",
              "age": 24,
              
            }
          ]
        }

I’ve tried this method after reading the JSON file

var newObject = array.reduce(function (obj, value) {
  var key = `${value.name}`;
  if (obj[key] == null) obj[key] = [];

  obj[key].push(value);
  return obj;
}, {});

console.log(newObject);

fs.appendFile("users.json", newObject, (err) => {
  res.send(JSON.stringify(newObject));
});

2

Answers


  1. You have to first read the data from the JSON and append the new object to the JSON data and then write it back to the file.

    const data = fs.readFileSync('users.json');
    .
    .
    fs.writeFileSync('users.json', {...data, ...newObject});
    
    Login or Signup to reply.
  2. Like the advice already given, but using async fs i/o.

    import { promises as fs } from 'fs';  // or require('fs').promises
    
    // inside the OP's route
      const filename = 'users.json';
      try {
        const array = await fs.readFile(filename);
    
        // OP's code here
        // const newObject = array.reduce(...
    
        await fs.writeFile(filename, newObject);
        return res.send(JSON.stringify(newObject));
    
      } catch (error) {
        return res.status(500).send({ message: 'error' });
      }
    

    Also note that all this is what a database does.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search