Skip to content

Instantly share code, notes, and snippets.

@Aldizh
Last active May 1, 2020 00:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aldizh/8f6b51aab36787f8f6cd97ae82bceb1c to your computer and use it in GitHub Desktop.
Save Aldizh/8f6b51aab36787f8f6cd97ae82bceb1c to your computer and use it in GitHub Desktop.
Utility for reducing array of objects
/*
Problem: Given an array of objects parse those objects
to form meaningful key value pairs
*/
// Input
const dataSource = [
{id: 48, code: "firstName", description: "John"},
{id: 49, code: "lastName", description: "Smith"},
{id: 49, code: "occupation", description: "Agent"},
{id: 47, code: "status", description: "Active"},
]
// Output
const output = {
firstName: "John",
lastName: "Smith",
occupation: "Agent",
status: "Active",
}
// Reduce Solution
const final = dataSource.reduce((accumulator, currentObj) => {
const newObj = {};
newObj[currentObj['code']] = currentObj['description'];
return Object.assign(accumulator, newObj);
}, {})
// Map solution (Gives you an array that needs to be coverted to an object)
const final2 = dataSource.map((obj) => ({
[obj.code]: obj.description
}))
console.log('Reduce method: ', final)
console.log('Map method: ', final2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment