Ginfo Ginfo - 3 months ago 42
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": "abs@abs.com",
"tel": "021269999999"
},
{
"id": "3",
"raison": "PODL",
"email": "abs@abs.com",
"tel": "021269999999"
}, {
"id": "5",
"raison": "dDMS",
"email": "abs@abs.com",
"tel": "021269999999"
}
]
}


in controller I have like this

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


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
["aaa","bob,"ccc"]
using
indexof()
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 .

Answer

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.

https://docs.angularjs.org/api/ng/function/angular.fromJson

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

$scope.datas= '{"count":3,"data": [{"id":"1","raison":"ABS","email":"abs@abs.com","tel":"021269999999"},{"id":"3","raison":"PODL","email":"abs@abs.com","tel":"021269999999"},{"id":"5","raison":"dDMS","email":"abs@abs.com","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
   $scope.exampleArray.data.splice(_id,1);
};

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

https://docs.angularjs.org/api/ng/function/angular.toJson