javascript根据搜索字词查找对象

时间:2011-04-21 07:40:51

标签: javascript search node.js underscore.js

我需要使用搜索项对象搜索对象数组,并在数组中获取结果索引。

假设我有一个这样的数组:

[
  {
    name: "Mary",
    gender: "female",
    country: "USA",
    orientation: "straight",
    colorChoice: "red",
    shoeSize: 7
  },
  {
    name: "Henry",
    gender: "male",
    country: "USA",
    orientation: "straight",
    colorChoice: "red",
  },
  {
    name: "Bob",
    colorChoice: "yellow",
    shoeSize: 10
  },
  {
    name: "Jenny",
    gender: "female",
    orientation: "gay",
    colorChoice: "red",
  }
]

现在我需要搜索数组:

{
  gender: "female"
}

得到结果:

[ 0, 3 ]

搜索对象可以是任意长度:

{
  gender: "female",
  colorChoice: "red"
}

搜索数组最干净,最高效的方法是什么?

感谢。

2 个答案:

答案 0 :(得分:2)

这应该可以解决问题:

function searchArray(fields, arr)
{
    var result = [];            //Store the results

    for(var i in arr)           //Go through every item in the array
    {
        var item = arr[i];
        var matches = true;     //Does this meet our criterium?

        for(var f in fields)    //Match all the requirements
        {
            if(item[f] != fields[f])    //It doesnt match, note it and stop the loop.
            {
                matches = false;
                break;
            }
        }

        if(matches)
            result.push(item);  //Add the item to the result
    }

    return result;
}

例如:

console.log(searchArray({
  gender: "female",
  colorChoice: "red"
},[
  {
    name: "Mary",
    gender: "female",
    country: "USA",
    orientation: "straight",
    colorChoice: "red",
    shoeSize: 7
  },
  {
    name: "Henry",
    gender: "male",
    country: "USA",
    orientation: "straight",
    colorChoice: "red",
  },
  {
    name: "Bob",
    colorChoice: "yellow",
    shoeSize: 10
  },
  {
    name: "Jenny",
    gender: "female",
    orientation: "gay",
    colorChoice: "red",
  }
]));

答案 1 :(得分:2)

以下是这个想法:

function getFemales(myArr){
 var i = myArr.length, ret = [];
 while (i--){
  if ('gender' in myArr[i] && myArr[i].gender === 'female') {
    ret.push(i);
  }
 }
 return ret.sort();
}

请参阅jsfiddle

更通用:

function findInElements(elArray, label, val){
 var i = elArray.length, ret = [];
 while (i--){
  if (label in elArray[i] && elArray[i][label] === val) {
    ret.push(i);
  }
 }
 return ret.sort();
}

请参阅jsfiddle