Neue Antwort
Ich habe die Requisite als Parameter hinzugefügt, um sie allgemeiner und wiederverwendbar zu machen
/**
* 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];
}
}
}
使用することです:
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');
Mokka-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);
});
});
Testergebnisse:
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)
Alte Antwort - wegen schlechter Praktiken entfernt
Wenn Sie mehr darüber wissen wollen, warum dies eine schlechte Praxis ist, lesen Sie diesen Artikel:
Warum ist die Erweiterung nativer Objekte eine schlechte Praxis?
Prototypische Version einer Array-Suche:
~~Array.prototype.search = function(key, prop){
for (var i=0; i < this.length; i++) {
if (this[i][prop] === key) {
return this[i];
}
}
}
使用することです:
var array = [
{ name:'string 1', value:'this', other: 'that' },
{ name:'string 2', value:'this', other: 'that' }
];
array.search('string 1', 'name');~~