我有这些数组对象
$scope.filters = {
1 : {
name : 'Pattern',
options : {
1 : { name: 'Plain', selected: false },
2 : { name: 'Self Design', selected: false },
3 : { name: 'Check', selected: false },
4 : { name: 'Stripe', selected: false },
5 : { name: 'Print', selected: false },
6 : { name: 'Others', selected: false }
}
},
2 : {
name : 'Colour',
options : {
1 : { name: 'White', selected: false },
2 : { name: 'Blue', selected: false },
3 : { name: 'Grey', selected: false },
4 : { name: 'Pink', selected: false },
5 : { name: 'Purple', selected: false },
6 : { name: 'Black', selected: false },
//7 : { name: 'Others', selected: false }
}
},
3 : {
name : 'Material',
options : {
1 : { name: 'Cotton', selected: false },
2 : { name: 'Technicals', selected: false },
3 : { name: 'CVC', selected: false },
4 : { name: 'Cotton, Two Ply', selected: false }
}
}
}
如何使用$ watch获取selected = true过滤器的组列表?
如果可能的话,我希望结果结构如下:
{
Pattern : {
1 : Plain,
2 : Self Design
},
Colour : {
1: Blue
}
}
答案 0 :(得分:1)
试试这个:
var name ,options, selected = {};
for (var idx in $scope.filters) {
name = $scope.filters[idx]['name'];
options = $scope.filters[idx]['options'];
for (var i in options) {
if(options[i]['selected']) {
selected[name] = selected[name] || {};
selected[name][i] = options[i]['name'];
}
}
}
console.log(JSON.stringify(selected,null,4));
/*
{
"Pattern": {
"1": "Plain",
"2": "Self Design"
},
"Colour": {
"2": "Blue"
}
}
*/
答案 1 :(得分:0)
看看这个plunkr。不是确切的解决方案,但会给你一个开始。
我使用$ watch(使用objectEquality参数)来获取更改的对象。然后,您可以使用underscore.js或纯JavaScript来过滤掉所选项目。