Skip to content

Instantly share code, notes, and snippets.

@ilmoralito
Last active September 19, 2017 23:07
Show Gist options
  • Save ilmoralito/2dca66ac6430529ba35d3caffded03da to your computer and use it in GitHub Desktop.
Save ilmoralito/2dca66ac6430529ba35d3caffded03da to your computer and use it in GitHub Desktop.
extracting non-repeated keys from a data list
// Given a set of data where the keys of the objects can vary
const data = [
{ name: 'Amanda', email: 'amanda@example.com', genre: 'Female' },
{ name: 'Daniel', email: 'daniel@example.com', genre: 'Male', telephones: ['8989 7667', '8765 4321'] },
{ name: 'Arnulfo', email: 'arnulfo@example.com', genre: 'Male', },
{ name: 'Ricardo', email: 'ricardo@example.com', genre: 'Male', city: 'Leon' },
{ name: 'Mario', genre: 'Male', single: true },
];
// Waiting for the next result: [ 'name', 'email', 'genre', 'telephones', 'city', 'single' ]
const result = data.reduce((accumulator, currentValue, index, self) => {
if (index === 0) accumulator.push(...Object.keys(currentValue));
const keys = Object.keys(currentValue).filter(key => accumulator.indexOf(key) === -1);
accumulator.push(...keys);
return accumulator;
}, []);
console.assert([ 'name', 'email', 'genre', 'telephones', 'city', 'single' ].join() === result.join(), 'Do not match');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment