Last active
March 27, 2018 14:19
-
-
Save dylansmith/f40f8cae99c42dee497d78b421dd3cb4 to your computer and use it in GitHub Desktop.
unkeyBy (inverse of _.keyBy)
This file contains hidden or 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
// 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