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

Looping through json object from a checkbox loop

本文关键字:循环 对象 json 遍历 复选框      更新时间:2023-09-26

我有一个 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}但我无法解决一个循环,它只返回哪些对象是真的。

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

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);

让我知道这是否有帮助。