从json角度删除项目

我有一个列表,当我点击一个项目,我生成一个输入文本,我在json中添加该输入的属性。 实际上,如果我点击列表中的项目多次,它会在json中添加所有那些时间我点击。 例如,如果我点击列表的第一项3次,我有这个json:

{ "newArray": [ { "attrname": "asd1", "attrValue": "", "attrType": "text" }, { "attrname": "asd1", "attrValue": "", "attrType": "text" }, { "attrname": "asd1", "attrValue": "", "attrType": "text" } ] } 

我想要的是,如果我点击1次我添加项目,然后如果我再次点击它从json中删除项目。 这是代码:

 
{{myNewArray}}

角部分:

 var myApp = angular.module('myApp',[]); myApp.controller("mycontroller", ["$scope", "$http", function($scope, $http){ $scope.getItems = { "data": [ { "label": "first", "objects": [ { "name": "firstObj", "attributes": [ { "attrname": "asd1", "attrValue": "", "attrType":"text" }, { "attrname": "asd2", "attrValue": "", "attrType":"text" } ] } ], "key": "bolla" }, { "label": "second", "objects": [ { "name": "secondObj", "attributes": [ { "attrname": "asd", "attrValue": "", "attrType":"text" }, { "attrname": "asd3", "attrValue": "", "attrType":"text" } ] } ], "key": "2" } ] }; $scope.filterSelected = $scope.getItems.data[0].objects; $scope.myNewArray = { newArray: [ ] } $scope.pushItems = function pushItems(items) { $scope.myNewArray.newArray.push(angular.copy(items)); console.log($scope.myNewArray); } }]); 

在这里jsfiddle https://jsfiddle.net/vuqcopm7/42/

谢谢

我不确定你真的想要推送数组中的项目副本,在像你这样的情况下,编写一个真实项目数组更有意义,这样你就可以操作数组项目,它也会反映在原文上。 在这种情况下,添加/删除将如下所示:

 $scope.pushItems = function pushItems(items) { var index = $scope.myNewArray.newArray.indexOf(items); if (index !== -1) { $scope.myNewArray.newArray.splice(index, 1); } else { $scope.myNewArray.newArray.push(items); } }; 

演示: https //jsfiddle.net/f5nxsqxm/

我会将属性JSON数组交换为对象文字,并使用属性名称作为键。 这将确保每个属性名称最多只有一个项目。 对象文字更像是一个字典,它看起来更接近你想要使用的字典。

在这里遍历对象文字也应该更高效。