Nik Nik - 1 year ago 212
JSON Question

How to delete item in JSON file

Hi Im trying to delete an object in a JSON file but it isnt working. I set the value p equal to the entire item which includes the values name, date and number. When I use delete in order to delete the specific item from the json file it doesn't get deleted. I was wondering if any of you knew why. Thanks.

here is the nodejs code

app.get('/testtwilio3', function(req,res,next){

var fs = require('fs');
var configFile = fs.readFileSync('./Public/patients.json');
var config = JSON.parse(configFile);
var p = {name:, date:, number: req.query.number};
var key = p;
delete config[key];
console.log( config);

Here is the code from the controller

$scope.deleteName = function($index){

var patient = {
name: $scope.patients[$index].name,
date: $scope.patients[$index].date,
$http.get('/testtwilio3', {params: {name:, number: patient.number, date:}}) // PASS THE DATA AS THE SECOND PARAMETER

console.log("error" + error)


Here is the json file


Here is what the console is displaying. First line is what I want to be deleted and the lines below it is the array of items.

{ name: 'Mark', date: '08/06/2016', number: '7819231279' }

[ { name: 'John', date: '12/22/2016', number: '781314454' },
{ name: 'Nikhilesh Singh',
date: '09/15/2016',
number: '7892834640' },
{ name: 'Mike', date: '08/25/2016', number: '6472329224' },
{ name: 'Mark', date: '08/06/2016', number: '7819231279' } ]

This is how I want it to be where the item in the first line has been removed form the list of items

{ name: 'Mark', date: '08/06/2016', number: '7819231279' }

[ { name: 'John', date: '12/22/2016', number: '781314454' },
{ name: 'Nikhilesh Singh',
date: '09/15/2016',
number: '7892834640' },
{ name: 'Mike', date: '08/25/2016', number: '6472329224' } ]

Answer Source


The delete operator is only for deleting a property from an object. Your config variable contains an array of objects, so delete will not do what you want at all.

You need to iterate through the config array and use something like splice to delete the array items that have the same name, date, and number values as in the request.

This related question might be helpful.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download