作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 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/
我是一名优秀的程序员,十分优秀!