JavaScript найти объекты на основе поисковых терминов - PullRequest
2 голосов
/ 21 апреля 2011

Мне нужно выполнить поиск в массиве объектов с помощью объекта поисковых терминов и получить индекс результатов в массиве.

Допустим, у меня есть такой массив:

[
  {
    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 ]

2 голосов
/ 21 апреля 2011

Вот идея:

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 голосов
/ 21 апреля 2011

Это должно сработать:

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",
  }
]));
...