Skip to content

Instantly share code, notes, and snippets.

@dylansmith
Last active March 27, 2018 14:19
Show Gist options
  • Save dylansmith/f40f8cae99c42dee497d78b421dd3cb4 to your computer and use it in GitHub Desktop.
Save dylansmith/f40f8cae99c42dee497d78b421dd3cb4 to your computer and use it in GitHub Desktop.
unkeyBy (inverse of _.keyBy)
// using map - fastest!
const unkeyBy = (obj, prop) => {
const res = [];
Object.keys(obj).map((x, i) => res[i] = { ...obj[x], [prop]: x });
return res;
};
// adds ungrouping
const ungroupBy = (obj, prop) => {
const res = [];
Object.keys(obj).map(k => {
const addKey = item => res.push({ ...item, [prop]: k });
Array.isArray(obj[k]) ? obj[k].map(addKey) : addKey(obj[k]);
});
return res;
};
// using reduce and destructuring
const unkeyBy = (obj, prop) => {
return Object.keys(obj).reduce((memo, key) => {
return [ ...memo, { ...obj[key], [prop]: key } ];
}, []);
};
// using reduce and concat
const unkeyBy = (obj, prop) => {
return Object.keys(obj).reduce((memo, key) => {
return memo.concat({ ...obj[key], [prop]: key });
}, []);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment