Skip to content

Instantly share code, notes, and snippets.

@bryzettler
Last active June 1, 2017 05:38
Show Gist options
  • Save bryzettler/89e6874705f12b23eca1dcc244b6826a to your computer and use it in GitHub Desktop.
Save bryzettler/89e6874705f12b23eca1dcc244b6826a to your computer and use it in GitHub Desktop.
const apiResponse = [
{first: 'Bob', favorite: 'The Clash'},
{first: 'Linda', favorite: 'Ramones'},
{first: 'Amy', favorite: 'The Clash'},
];
const friendConstants = ['Bob', 'Amy', 'James', 'Tiffany', 'Linda'];
friendConstants.reduce((acc, friend, idx, orgArray) => ({
// Check for friend in apiResponse
// if there pull them out otherwise we create a default objecct
acc = {
...acc,
[friend]: apiResponse.find({ first: friend }) || { first: friend, favorite: 'Unknown' },
};
// if we're on the last item in the array
// return only the values of the acc
// otherwise return acc and go to next iteration
return idx === (orgArray.length - 1) ?
Object.values(acc) :
acc;
}), {});
// initalValue is an Object. But we'll get back an array
/*
=> [
{first: 'Bob', favorite: 'The Clash'},
{first: 'Amy', favorite: 'The Clash'},
{first: 'James', favorite: 'Unknown'},
{first: 'Tiffany, favorite: 'Unknown'},
{first: 'Linda', favorite: 'Ramones'},
];
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment