0

I have an array of javascript objects, each with three fields, like this:

var people = [
  {first: "john", middle: "james", last: "doe"},
  {first: "jane", middle: "kate", last: "smith"},
  ...
  {first: "kathy", middle: "rose", last: "green"},
];

I want to be able to query this array based on any of the fields, and get back the object which matches. For instance I want to be able to call something like people.getByMiddle("kate") and get back {first: "jane", middle: "kate", last: "smith"}

Is there a data structure that makes associating these things in this way easier, or should I just write three separate functions each of which iterates over my data and searches for a match? I don't want anything that relies on the ordering of arrays.

kat
  • 5,645
  • 4
  • 19
  • 35
  • 1
    You can just write one function that takes the property name to be searched as well as the value to match. – Alfredo Delgado Sep 08 '15 at 19:54
  • Do you want to do it yourself or are you okay with including libraries? – CherryNerd Sep 08 '15 at 19:55
  • 2
    Possible duplicate of [Get javascript object from array of objects by value or property](http://stackoverflow.com/questions/13964155/get-javascript-object-from-array-of-objects-by-value-or-property) OR [Find object by id in array of javascript objects](http://stackoverflow.com/questions/7364150/find-object-by-id-in-array-of-javascript-objects) (Several functional answers in each.) – showdev Sep 08 '15 at 19:55
  • @showdev It's not a duplicate. He already knows how to search by a specific property, he wants to know how to generalize it to any property. – Barmar Sep 08 '15 at 19:56
  • @showdev He wants to know how to write a single function instead of separate `getByMiddle`, `getByFirst`, `getByLast` functions. – Barmar Sep 08 '15 at 19:59
  • @Barmar I see. The other posts I linked may not be specific enough, though I think they inspire solutions. [This answer](http://stackoverflow.com/questions/7364150/find-object-by-id-in-array-of-javascript-objects#answer-11477986), for example, addresses generalization. I have not voted to close. – showdev Sep 08 '15 at 20:06

4 Answers4

2

You can define a helper function:

/**
 * Filter an array of objects and return the first matching element.
 * @param {array} collection - an array of objects.
 * @param {string} key 
 * @param {string} value
 * @returns {object|undefined} - the first matching object.
 */
function findWhere(collection, key, value) {
   return collection.filter(function(o) {
      return o[key] === value;
   })[0]; // get the first matching element
};

var person = findWhere(people, 'middle', 'kate');
Ram
  • 143,282
  • 16
  • 168
  • 197
1
function getByProperty (arr, prop, value) {
    arr.forEach(function (item) {
        if (item[prop] === value) {
            return item;
        }
    });
}

Where you'd use it like this:

var result = getByProperty(people, 'middle', 'kate');
Davion
  • 881
  • 6
  • 12
1

Here's a possible solution:

function findPeople(anArray, objProperty, searchPattern) {
  return anArray.filter(function(person){
    return searchPattern.test(person[objProperty]);
  })
}

Working example: http://jsbin.com/xavogojaxo/edit?js,console

Alfredo Delgado
  • 689
  • 4
  • 12
0

I can only think of this:

var people = [
  {first: "john", middle: "james", last: "doe"},
  {first: "jane", middle: "kate", last: "smith"},
  {first: "kathy", middle: "rose", last: "green"},
];


people.getByMiddle = function(name){ 
   var newSelection = [];
   for(i in this){
      var item = this[i];
      if(item.middle == name)
         newSelection.push(item);
   }
   return newSelection;
};

people.getByMiddle("kate");
Marcus Abrahão
  • 696
  • 1
  • 8
  • 18