gpt4 book ai didi

javascript - 从复选框循环遍历 json 对象

转载 作者:行者123 更新时间:2023-11-28 07:49:14 24 4
gpt4 key购买 nike

我有一个 json 对象,正在通过 ng-repeat 中的复选框加载。它列出了可能的服务,我正在尝试访问提交表单时已检查的服务。

我通过以下方式加载复选框:

<label style="margin-right:10px" ng-repeat="item in dsServces">
<input
type="checkbox"
name="selectedFruits"
value="{{item.DefaultServiceID}}"
ng-model="expense.dsService[item.DefaultServiceName]"
> {{item.DefaultServiceName}}
</label>

我可以通过测试看到费用正在建立:

{{ expense.dsService }}

返回(当选择一对时)

{"Email":true,"Backups":true}

但我不知道如何循环,所以它只显示服务名称,以便我可以针对客户添加它们。

在后端我有:

$scope.expense = {
tags: []
};

提交时:

 angular.forEach($scope.expense, function(item) {
console.log(item);
});

其中输出 Object {Email: true, Backups: true} 但我无法找到一个循环,它只返回哪个对象为 true。

我的主要目标是拥有类似的东西

angular.forEach(forloop) {
//service.item should be like 'Email' whatever the item.DefaultServiceName is
// the loop should be all items that are checked
addService(service.item);
});

最佳答案

如果我理解正确,您希望将对象的键值插入数组中。如果是这种情况,只需对您的 forEach()

进行一些更改即可

像这样:

// The first parameter is what you want to loop through
// Second is the iterator, you can separate out the key and values here
// The third is the context, since I put the array we want to push to in here
// we just need to call `this.push()` within the iterator
angular.forEach($scope.expense, function(value, key) {
this.push(key);
}, $scope.expense.tags);

请告诉我这是否有帮助。

关于javascript - 从复选框循环遍历 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27062233/

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