New answer
I added the prop as a parameter, to make it more general and reusable
/**
* Represents a search trough an array.
* @function search
* @param {Array} array - The array you wanna search trough
* @param {string} key - The key to search for
* @param {string} [prop] - The property name to find it in
*/
function search(array, key, prop){
// Optional, but fallback to key['name'] if not selected
prop = (typeof prop === 'undefined') ? 'name' : prop;
for (var i=0; i < array.length; i++) {
if (array[i][prop] === key) {
return array[i];
}
}
}
Usage:
var array = [
{
name:'string 1',
value:'this',
other: 'that'
},
{
name:'string 2',
value:'this',
other: 'that'
}
];
search(array, 'string 1');
// or for other cases where the prop isn't 'name'
// ex: prop name id
search(array, 'string 1', 'id');
Mocha test:
var assert = require('chai').assert;
describe('Search', function() {
var testArray = [
{
name: 'string 1',
value: 'this',
other: 'that'
},
{
name: 'string 2',
value: 'new',
other: 'that'
}
];
it('should return the object that match the search', function () {
var name1 = search(testArray, 'string 1');
var name2 = search(testArray, 'string 2');
assert.equal(name1, testArray[0]);
assert.equal(name2, testArray[1]);
var value1 = search(testArray, 'this', 'value');
var value2 = search(testArray, 'new', 'value');
assert.equal(value1, testArray[0]);
assert.equal(value2, testArray[1]);
});
it('should return undefined becuase non of the objects in the array have that value', function () {
var findNonExistingObj = search(testArray, 'string 3');
assert.equal(findNonExistingObj, undefined);
});
it('should return undefined becuase our array of objects dont have ids', function () {
var findById = search(testArray, 'string 1', 'id');
assert.equal(findById, undefined);
});
});
test results:
Search
✓ should return the object that match the search
✓ should return undefined becuase non of the objects in the array have that value
✓ should return undefined becuase our array of objects dont have ids
3 passing (12ms)
Old answer - removed due to bad practices
if you wanna know more why it's bad practice then see this article:
Why is extending native objects a bad practice?
Prototype version of doing an array search:
Array.prototype.search = function(key, prop){
for (var i=0; i < this.length; i++) {
if (this[i][prop] === key) {
return this[i];
}
}
}
Usage:
var array = [
{ name:'string 1', value:'this', other: 'that' },
{ name:'string 2', value:'this', other: 'that' }
];
array.search('string 1', 'name');