Last active
May 1, 2020 00:38
-
-
Save Aldizh/8f6b51aab36787f8f6cd97ae82bceb1c to your computer and use it in GitHub Desktop.
Utility for reducing array of objects
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
/* | |
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