gpt4 book ai didi

javascript - 从 json 中删除项目,再次点击

转载 作者:行者123 更新时间:2023-12-02 16:09:31 25 4
gpt4 key购买 nike

我前段时间问过如何更准确地从 json 中删除项目:Angular remove item from json

并且效果很好..现在我遇到了同样的问题,但代码有点不同。总之,我有一个 list 。当我单击某个项目时,它会在 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"}]}]}

最佳答案

您可以大大简化代码,如下所示:

HTML

 <ul ng-repeat="item in att.attributes">
<li>
<a ng-click="pushItems(item)">{{item.attrname}}</a>
</li>
</ul>

JS

$scope.pushItems = function pushItems(item) { // note only single argument now
// index the whole item object
var itemIndex = $scope.myNewArray.objects.indexOf(item);
if (itemIndex == -1) {
// if index doesn't exist ...add to array
$scope.myNewArray.objects.push(item);
} else {
// otherwise remove from array
$scope.myNewArray.objects.splice(itemIndex, 1);
}
}

通过使用对象本身,您不需要查看对象的属性来检查它是否存在,而是检查实际对象的索引

DEMO

关于javascript - 从 json 中删除项目,再次点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30374113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com