Sergey Metlov
Sergey Metlov

Reputation: 26331

Array selector function by property value

I have:

var array = [ { key: '1' }, { key: '2' }, { key: '3' } ]

I want:

var obj = getFirstItem(array, 'key', '2');

And as a result:

obj = { key: '2' }

Is there such function in JavsScript or jQuery?

Upvotes: 2

Views: 4090

Answers (3)

Richard Dalton
Richard Dalton

Reputation: 35793

Like others have said it's quite simple to just loop over the array yourself.

However there is a filter method in JS 1.5 (Apparently not supported in IE8 and lower, although the link has a compatibility work around)

var myarray = [ { key: '1' }, { key: '2' }, { key: '3' } ]

function getFirstItem(myarray, key) {
    var result = myarray.filter(function(element, index, array) { 
        return element.key == key;  
    });
    if (result.length) 
        return result[0];
    return null;
}

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter

JSFiddle Example

Upvotes: 0

Jamiec
Jamiec

Reputation: 136154

I don't think jQuery is really necessary here. The function is as simple as:

function getFirstItem(arr, k, v){
    for(var i=0;i<arr.length;i++){
      var obj = arr[i];
      if(obj[k] == v)
          return obj;  
    }
    return null;
}

Live example: http://jsfiddle.net/QARAd/

Upvotes: 1

alexn
alexn

Reputation: 59002

I don't know of a built in function. However, it would be trivial to implement it yourself:

var data = [ { key: '1' }, { key: '2' }, { key: '3' } ];

function getFirstItem(input, key, value) {
    for(var i = 0; i < input.length; i++) {
        if(input[i][key] === value)
            return input[i];
    }
}

console.log(getFirstItem(data, "key", 2));

Upvotes: 3

Related Questions