Skip to content

Instantly share code, notes, and snippets.

@Aldizh Aldizh/reduce_for_objects

Last active May 1, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.