Skip to content

Instantly share code, notes, and snippets.

@jmorenoamor
Created March 29, 2020 07:24
Show Gist options
  • Save jmorenoamor/e21b9bad4e842c3d892544bc66af3a5e to your computer and use it in GitHub Desktop.
Save jmorenoamor/e21b9bad4e842c3d892544bc66af3a5e to your computer and use it in GitHub Desktop.
Transform an array of objets to an object by selected key
// Input array
const peopleArray = [
{ id: 123, name: "dave", age: 23 },
{ id: 456, name: "chris", age: 23 },
{ id: 789, name: "bob", age: 23 },
{ id: 101, name: "tom", age: 23 },
{ id: 102, name: "tim", age: 23 }
]
// Simple function
const arrayToObject = (array, keyField) => array.reduce((total, current) => {
total[current[keyField]] = current;
return total;
}, {});
// Call
console.log(arrayToObject(peopleArray, "name"))
// Inline
peopleArray.reduce((total, current) => {
total[current["name"]] = current;
return total;
}, {});
// Transform objetc key function
const arrayToObjectTransform = (array, keyField, transform) => array.reduce((total, current) => {
total[transform(current[keyField])] = current;
return total;
}, {});
// Call
const upper = (value) => value.toUpperCase();
console.log(arrayToObjectTransform(peopleArray, "name", upper));
console.log(arrayToObjectTransform(peopleArray, "name", (v) => v.toUpperCase()));
// Inline
peopleArray.reduce((total, current) => {
total[upper(current["name"])] = current;
return total;
}, {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment