How To Replace Old Json Object With A New One With Nodejs
How to replace old json object using NodeJS with a new updated object ? Right now when i update the json file it saves the new data with the old one. JSON : [ { 'id': 1, '
Solution 1:
My assumption base on your question is that you have multiple objects in one file. So the easy way to work around this would be to
if (operation == 'update') {
fs.readFile("file.json", "utf8", function (err, data) {
var jsonFileArr = [];
jsonFileArr = JSON.parse(data); //Parse the data from JSON filevar haveId = jsonFileArr.some(function (obj){ // Checks if the POST request have the same id as JSON filereturn obj.id == POST.id;
})
if (haveId) { // if truevar updateData = []; // Array with POST data
updateData.push({
id: POST.id,
name: POST.name,
phone: POST.phone,
})
for(letArrof jsonFileArr){
if (Arr.id == POST.id){
let currentIndex = jsonFileArr.indexOf(Arr);
jsonFileArr.splice(currentIndex,1,updateData) //removing the old object and adding the new one
}
}
var newUsers = JSON.stringify(jsonFileArr);
fs.writeFile("file.json", '', "utf8",function(err,res){ //Making the file emptyif(!err){
fs.writeFile("file.json", newUsers, "utf8",function(err,res){ //Writing the whole object backif(err)console.log(err);
console.info(res);
});
}else{
console.log(err);
}
});
}
})
}
I think this is better instead of using some, get the matching index and replace directly.
var jsonFileArr = JSON.parse(data); //Parse the data from JSON filevar foundId = jsonFileArr.findIndex(function (obj){ // Checks if the POST request have the same id as JSON filereturn obj.id == POST.id;
});
if (foundId >= 0) {
jsonFileArr[foundId] =
{
id: POST.id,
name: POST.name,
phone: POST.phone,
}
}
.... and then write back to file
Post a Comment for "How To Replace Old Json Object With A New One With Nodejs"