Skip to content

Instantly share code, notes, and snippets.

@psenger
Last active October 29, 2020 22:04
Show Gist options
  • Select an option

  • Save psenger/d9457c208166d6db3ba0662afa76fcb4 to your computer and use it in GitHub Desktop.

Select an option

Save psenger/d9457c208166d6db3ba0662afa76fcb4 to your computer and use it in GitHub Desktop.
[Create an Index Object from an Array of values, based on a passed attribute's value] #JavaScript #Array
// Creates a Dictionary / Index Object for all the objects based on the passed attribute value.
/**
* Create an object with keys based on a passed attribute within the array of values
* @param {[*]} objects - array of objects
* @param {string} attributeName - the attribute name
* @return {*}
*/
var indexByAttribute = function indexByAttribute ( objects, attributeName ) {
return (objects||[])
.reduce(function reducer(previousValue,currentValue,currentIndex,array) {
if( currentValue && previousValue.hasOwnProperty( currentValue[attributeName] ) ) {
// previousValue[ currentValue[attributeName] ].push( currentValue );
throw new Error('non unique value encountered in objects')
} else if ( currentValue ) {
previousValue[ currentValue[attributeName] ] = currentValue ;
}
return previousValue
}, {});
}
let x = {
"keys": [
{
"kid": "747527d1-12f6-4e58-a7dd-394dd9161a99",
"kty": "RSA",
"alg": "RS256",
"use": "sig",
"n": "2898e1e0-cebf-44e0-bc20-8d5b868e170b-fae7028a-dbae-483a-9849-390ca82d6282-d7910462-c128-4c7d-88ba-ca48efee0839",
"e": "AQAB"
},
{
"kid": "c9567bf8-5684-40fc-bc24-858d493042b8",
"kty": "RSA",
"alg": "RS256",
"use": "sig",
"n": "b3236ed7-75c3-4e78-9fd9-b464060469b7-bd04a9e6-78d5-4f40-b8da-19c879d5d51a-d7910462-c128-4c7d-88ba-ca48efee0839",
"e": "AQAB"
},
]
}
console.log(JSON.stringify( indexByAttribute( x.keys, 'kid' ) , null, 4));
/**
{
"747527d1-12f6-4e58-a7dd-394dd9161a99": {
"kid": "747527d1-12f6-4e58-a7dd-394dd9161a99",
"kty": "RSA",
"alg": "RS256",
"use": "sig",
"n": "2898e1e0-cebf-44e0-bc20-8d5b868e170b-fae7028a-dbae-483a-9849-390ca82d6282-d7910462-c128-4c7d-88ba-ca48efee0839",
"e": "AQAB"
},
"c9567bf8-5684-40fc-bc24-858d493042b8": {
"kid": "c9567bf8-5684-40fc-bc24-858d493042b8",
"kty": "RSA",
"alg": "RS256",
"use": "sig",
"n": "b3236ed7-75c3-4e78-9fd9-b464060469b7-bd04a9e6-78d5-4f40-b8da-19c879d5d51a-d7910462-c128-4c7d-88ba-ca48efee0839",
"e": "AQAB"
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment