【发布时间】:2015-05-21 12:41:27
【问题描述】:
我曾经问过如何更准确地从 json 中删除一个项目:Angular remove item from json
它运行良好.. 现在我遇到了同样的问题,但代码有点不同。总之,我有一个清单。当我单击一个项目时,它会将其属性添加到 json 中。我希望如果我再次单击此项目,它会从 json 中删除其属性。因此,我单击 Item1 并添加,再次单击 Item1 并删除。
这是我尝试过的
myApp.controller("mycontroller", ["$scope", "$http",
function($scope, $http){
$scope.getItems = {
"data": [
{
"label": "first",
"objects": [
{
"name": "firstObj",
"attributes": [
{
"attrname": "Item1",
"attrValue": "",
"attrType":"text"
},
{
"attrname": "Item2",
"attrValue": "",
"attrType":"text"
}
]
}
],
"key": "bolla"
}
]
};
$scope.filterSelected = $scope.getItems.data[0].objects;
$scope.myNewArray = {
objects: [
]
}
$scope.createjson = function(attribute, items) {
var obj = {};
obj.name = attribute;
obj.attributes = [];
obj.attributes.push(items);
return obj;
}
$scope.checkIfAttributeExists = function(attribute) {
for(var i=0; i<$scope.myNewArray.objects.length; i++) {
if($scope.myNewArray.objects[i]["name"] == attribute) {
return i;
}
}
return -1;
}
$scope.pushItems = function pushItems(attribute, items) {
var index = $scope.checkIfAttributeExists(attribute);
if(index == -1) {
var obj = $scope.createjson(attribute, items);
$scope.myNewArray.objects.push(obj);
} else if(index !== -1) {
$scope.myNewArray.objects.splice(index, 1);
}else {
$scope.myNewArray.objects[index].attributes.push(items);
}
}
$scope.showNewJson = function() {
return $scope.myNewArray;
}
}]);
似乎问题出在索引中。在这里我创建了一个 jsFiddle:
更新链接: https://jsfiddle.net/vuqcopm7/53/
其实这就是代码的作用:
{"objects":[{"name":"firstObj","attributes":[{"attrname":"Item1","attrValue":"","attrType":"text"}]},{"name":"firstObj","attributes":[{"attrname":"Item1","attrValue":"","attrType":"text"}]},{"name":"firstObj","attributes":[{"attrname":"Item2","attrValue":"","attrType":"text"}]}]}
如您所见,属性“Item1”有两次,因为我在它上面单击了两次。但是,如果我单击两次,Item1 就会消失!所以正确的json是:
{"objects":[{"name":"firstObj","attributes":[{"attrname":"Item2","attrValue":"","attrType":"text"}]}]}
【问题讨论】:
-
对您的代码的一点建议:您的函数定义是 $scope.checkIfAttributeExists = function(attribute) { ...,而实际调用是 "var index = $scope.checkIfAttributeExists(items); "太混乱了!
-
我更新了fiddle的链接
-
不要将属性值传递给函数,而是使用整个对象。您的代码远比需要的复杂。还要了解
json是什么。您不是在创建或使用 json,而是在使用 javascript 对象和数组。json只是一种类似于 javascript 对象和数组的字符串数据传输格式 -
该数组是我将发送到服务器的内容。但我必须发送我需要的内容。因此,选择的每个项目都有 1 个属性。不多。明白了吗?
-
尝试查看我对任务的小编辑
标签: javascript jquery json angularjs