我有这样的模特:
var model = [{id: 1, prices: [{count: 2}, {count: 3}]}, {id: 2, prices: [{count: 2}]}, {id: 3, prices: [{count: 3}]}];
我需要过滤数组使用属性count
的这些对象,我需要在三种情况下返回匹配的对象:
prices
中有两个对象,prices
中有一个匹配count:2
,prices
中有一个匹配count:3
的属性。所以..当我点击没有指定值的按钮时我想看到所有对象,当我点击值为2的按钮时我想看到有计数的对象:2当我点击值为3的按钮时我想得到对象数:3,我必须在AngularJS中做到这一点 -
答案 0 :(得分:0)
也许是这样的?
var result = model.filter(function(m) {
// make sure the m.prices field exists and is an array
if (!m.prices || !Array.isArray(m.prices)) {
return false;
}
var numOfPrices = m.prices.length
if (numOfPrices === 2) { // return true if its length is 2
return true;
}
for (var i = 0; i < numOfPrices; i++) {
if (m.prices[i].count &&
(m.prices[i].count === 2 ||
m.prices[i].count == 3)) {
return true;
}
}
return false;
});
答案 1 :(得分:0)
使用lodash或下划线库..然后你的代码与lodash将是:
_.filter(model, function(i){
return _.intersection(_.map(i.prices, 'count'), [3,2]).length;
})
它返回其price属性上的项目包含count = 3或count = 2
的元素的数组答案 2 :(得分:0)
var model = [{
id: 1,
prices: [{
count: 2
}, {
count: 3
}]
}, {
id: 2,
prices: [{
count: 2
}]
}, {
id: 3,
prices: [{
count: 3
}]
}];
var search = function(data) {
var result = {};
function arrayObjectIndexOf(myArray, searchTerm, property) {
for (var i = 0, len = myArray.length; i < len; i++) {
if (myArray[i][property] === searchTerm) return i;
}
return -1;
}
for (var index in data) {
if (data[index].hasOwnProperty("prices") && arrayObjectIndexOf(data[index].prices, 2, 'count') != -1) {
result[data[index].id] = data[index];
} else if (data[index].hasOwnProperty("prices") && arrayObjectIndexOf(data[index].prices, 3, 'count') != -1) {
result[data[index].id] = data[index];
} else if (data[index].hasOwnProperty("prices") &&
data[index].prices.length == 2) {
result[data[index].id] = data[index];
}
}
return result;
}
var output = search(model);
console.log(output);