Ginfo Ginfo - 1 month ago 14x
JSON Question

Remove item from json file using angularjs

I lost a lot of time trying to delete a item from Json file

This is my json file

"count": 3,
"data": [
"id": "1",
"raison": "ABS",
"email": "",
"tel": "021269999999"
"id": "3",
"raison": "PODL",
"email": "",
"tel": "021269999999"
}, {
"id": "5",
"raison": "dDMS",
"email": "",
"tel": "021269999999"

in controller I have like this

$scope.deleteRow = function() {
var _id = 3;
$scope.datas = JSON.stringify($scope.clients["data"]);

so i gave _id that i want to remove but i get this error $scope.datas.splice splice not a function, i tried a simple file it worked fine
and splice but in this file json non :(

How in javascript can Know/compare the right id ?

so anyone help me , and thanks a lot .


Using splice() will not work since the JSON itself doesn't have access to Javascript array functions. A solution to this would be using angular's fromJson() function which will convert it into a workable Javascript array.

Using the fromJson() function we can apply this to your JSON:

$scope.datas= '{"count":3,"data": [{"id":"1","raison":"ABS","email":"","tel":"021269999999"},{"id":"3","raison":"PODL","email":"","tel":"021269999999"},{"id":"5","raison":"dDMS","email":"","tel":"021269999999"}]}'

$scope.exampleArray = angular.fromJson($scope.datas);

Doing that will convert it and make it usable. From there, you can take your code and modify it a little bit so that it will work with our new object:

$scope.deleteRow = function() {
   var _id = 2; // Using 2 rather than 3 because of array indexes

Afterwards Angular also has a way to convert our object back into a usable JSON object using its suprisingly named counter-part; toJson()