【问题标题】:javascript find objects based on search termsjavascript 根据搜索词查找对象
【发布时间】:2011-08-10 02:34:46
【问题描述】:

我需要用一个搜索词的对象搜索一个对象数组,并在一个数组中获取结果的索引。

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

[
  {
    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"
}

什么是搜索数组的最简洁和最高效的方法?

谢谢。

【问题讨论】:

标签: javascript search node.js underscore.js


【解决方案1】:

这就是想法:

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

【讨论】:

【解决方案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",
  }
]));

【讨论】:

  • 您也可以编辑函数以返回数组的索引 (i),只需将其推送到结果数组而不是项目上。
猜你喜欢
  • 2012-04-26
  • 1970-01-01
  • 1970-01-01
  • 2020-11-20
  • 1970-01-01
  • 1970-01-01
  • 2011-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多