Here is an example that is a prototype of an Array object. Note: this is shown, for example - find not a good name for this function, and it probably will not be needed for all arrays
Instead, consider only using a function definition and creating a function of type getObjVal , calling both getObjVal(arr,'propName') , as well as LaurenT's answer.
Considering
var arr = [{key:'value'},{key2:'value2'}];
Definition
// for-loop example Array.prototype.find = function (prop){ for(var i=this.length; i--; ) if (typeof this[i][prop] !== 'undefined') return this[i][prop]; return undefined; } // for-each loop example Array.prototype.find = function (prop){ for (var i in this) if ( this.hasOwnProperty(i) && typeof this[i][prop] !== "undefined" ) return this[i][prop]; return undefined; }
Using
console.log( arr.find('key2') ); // 'value2' console.log( arr.find('key3') ); // undefined
vol7ron
source share