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
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.
Like the advice already given, but using async fs i/o.
Also note that all this is what a database does.