简体   繁体   中英

how to push a data with key of an array of objects without overwriting existing json data using node js?

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));
});

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.

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});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM