过滤对象数组

时间:2014-09-29 13:49:18

标签: javascript object

我通过API从MongoDB获取了一组对象。

然后我需要进一步过滤结果(客户端)。

我将使用长列表(可能有数千个结果),每个对象有大约10个属性,其中包含一些数组。

对象示例:

{
  _id: xxxxxxx,
  foo: [
    { a: "b", c: "d" },
    { a: "b", c: "d" }    
  ],
  data: {
    a: "b",
    c: "d"
  }
}

我将数组循环异步以提高速度:

async.filter(documents, function(value) {
  // Search inside the object to check if it contains the given "value"
}, function(results) {
  // Will do something with the result array
});

如何在当前对象内搜索以检查它是否包含给定值而不知道我将在哪个属性中找到该值?

2 个答案:

答案 0 :(得分:0)

虽然我没有包含async部分,但我相信整体搜索方法可能是这样的:



// Input Array
var inpArr = [{
  id: 1,
  foo: [{
    a: "dog",
    b: "cat"
  }]
}, {
  id: 2,
  foo: [{
    a: "kutta",
    b: "billi"
  }]
}];


var myFilter = function(val, item, index, array) {

  var searchResult = scanProperties(item, val);
  return searchResult;
};


// Note: pass additional argument to default filter.
// using Function.Prototype.Bind
var filterResult = inpArr.filter(myFilter.bind(null, "dog"));

alert(filterResult);
console.log(filterResult);

// Recursively scan all properties
function scanProperties(obj, val) {

  var result = false;
  for (var property in obj) {
    if (obj.hasOwnProperty(property) && obj[property] != null) {
      if (obj[property].constructor == Object) {
        result = result || scanProperties(obj[property], val);
      } else if (obj[property].constructor == Array) {
        for (var i = 0; i < obj[property].length; i++) {
          result = result || scanProperties(obj[property][i], val);
        }
      } else {
        result = result || (obj[property] == val);
      }
    }
  }
  return result;
};
&#13;
&#13;
&#13;

JS小提琴Searching an Array of Objects

答案 1 :(得分:0)

您可以简单地递归遍历每个项目,例如

var data = {
    _id: 1243,
    foo: [{
        a: "b",
        c: "d"
    }, {
        a: "b",
        c: "d"
    }],
    data: {
        a: "b",
        c: "d"
    }
};

function findValue(value) {
    function findItems(document) {
        var type = Object.prototype.toString.call(document);
        if (type.indexOf("Array") + 1) {
            return document.some(findItems);
        } else if (type.indexOf("Object") + 1) {
            return Object.keys(document).some(function(key) {
                return findItems(document[key]);
            });
        } else {
            return document === value;
        }
    }
    return findItems;
}
console.log(findValue('dd')(data));
# false
console.log(findValue('d')(data));
# true
相关问题