Last active
December 19, 2015 14:28
-
-
Save Rich-Harris/5969002 to your computer and use it in GitHub Desktop.
Reindex an array by a common property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://gist.github.com/Rich-Harris/5969002 | |
// ------------------------------------------- | |
// | |
// MIT licensed. Go nuts. | |
(function ( global ) { | |
'use strict'; | |
var reindex = function ( array, idField ) { | |
var obj = {}, i, record; | |
if ( Object.prototype.toString.call( array ) !== '[object Array]' ) { | |
throw new Error( 'Cannot reindex a non-array!' ); | |
} | |
if ( !idField ) { | |
throw new Error( 'You must specify an ID field' ); | |
} | |
i = array.length; | |
while ( i-- ) { | |
record = array[i]; | |
if ( record.hasOwnProperty( idField ) ) { | |
obj[ record[ idField ] ] = record; | |
} | |
} | |
return obj; | |
}; | |
// export as CommonJS module... | |
if ( typeof module !== 'undefined' && module.exports ) { | |
module.exports = reindex; | |
} | |
// ... or as AMD module... | |
else if ( typeof define !== 'undefined' && define.amd ) { | |
define( function () { return reindex; }); | |
} | |
// ... or as browser global | |
else { | |
global.reindex = reindex; | |
} | |
}( this )); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: