如何过滤嵌套在数组对象属性中的对象数组

How do i filter array of objects nested in property of array objects?

本文关键字:对象 数组 属性 嵌套 何过滤 过滤      更新时间:2023-09-26

我有一个这样的模型:

var model = [{id: 1, prices: [{count: 2}, {count: 3}]}, {id: 2, prices: [{count: 2}]}, {id: 3, prices: [{count: 3}]}];

,我需要使用属性count过滤数组的对象,我需要在三种情况下返回匹配的对象:

  1. 如果对象在数组prices中有两个对象,
  2. 如果对象在prices数组中有一个对象匹配count:2
  3. 如果对象在数组prices中有一个属性匹配count:3

. .当我点击没有指定值的按钮时,我想看到所有对象,当我点击value = 2的按钮时,我想看到count: 2的对象,当我点击value = 3的按钮时,我想得到count: 3的对象,我必须在AngularJS中这样做-

也许是这样的?

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

使用lodash或下划线库..然后你的lodash代码会像这样:

_.filter(model, function(i){
   return _.intersection(_.map(i.prices, 'count'), [3,2]).length;
})

返回price属性中包含count = 3或count = 2元素的数组

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