最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove a object from a JSON object list - Stack Overflow

programmeradmin2浏览0评论

HTML code:

<li ng-repeat="obj in objects">{{obj.name}} <a ng-click="remove($index)">x</a></li> 

JavaScript code:

$scope.remove = function(index){
    $scope.objects.splice(index, 1);
}

JSON data:

{
    "0": { "name": "name1" },
    "1": { "name": "name2" }
}

When remove() is called, I get TypeError: $scope.objects.splice is not a function, here I know $scope.objects is not an array and so splice() will not work.

Is there any method to remove the selected index??

Thanks in advance...

HTML code:

<li ng-repeat="obj in objects">{{obj.name}} <a ng-click="remove($index)">x</a></li> 

JavaScript code:

$scope.remove = function(index){
    $scope.objects.splice(index, 1);
}

JSON data:

{
    "0": { "name": "name1" },
    "1": { "name": "name2" }
}

When remove() is called, I get TypeError: $scope.objects.splice is not a function, here I know $scope.objects is not an array and so splice() will not work.

Is there any method to remove the selected index??

Thanks in advance...

Share Improve this question edited Apr 19, 2015 at 21:44 Misa Lazovic 2,82310 gold badges33 silver badges39 bronze badges asked Apr 19, 2015 at 21:07 sathish salvadorsathish salvador 3205 silver badges16 bronze badges 7
  • 4 delete $scope.objects[index] – adeneo Commented Apr 19, 2015 at 21:08
  • Need more code for $scope creation – MaxZoom Commented Apr 19, 2015 at 21:16
  • The solution by @adeneo worked, but while removing there seems to be another issue, jsfiddle/salvadorcs/9d8ztbpL – sathish salvador Commented Apr 19, 2015 at 21:32
  • when i remove name2 and then name1 it works fine, but the other way the name2 is not removed – sathish salvador Commented Apr 19, 2015 at 21:33
  • the indexes of $scope.objects remains same after calling remove() – sathish salvador Commented Apr 19, 2015 at 21:39
 |  Show 2 more ments

1 Answer 1

Reset to default 4

Since you're using a json object and not an array you can use ng-repeat like this

<li ng-repeat="(key,value) in objects">{{value.name}} <a ng-click="remove(key)">x</a></li> 

So that the remove method can delete current list element by key:

$scope.remove = function(key) {
     delete $scope.objects[key];
}

Here's a plunker.

$index is quite confusing in cases like this as it is dynamic whereas the keys are not.

发布评论

评论列表(0)

  1. 暂无评论