Skip to content

Instantly share code, notes, and snippets.

@joeytwiddle
Created June 21, 2018 09:57
Show Gist options
  • Save joeytwiddle/ea27d537585894830154fdaa797a079d to your computer and use it in GitHub Desktop.
Save joeytwiddle/ea27d537585894830154fdaa797a079d to your computer and use it in GitHub Desktop.
Some Array functions for Objects
// The functional way
const objUtils = {
mapProps(obj, mapFn) {
return Object.entries(obj).reduce((a, [key, value]) => (
{ ...a, [key]: mapFn(value) }
), {});
},
filterProps(obj, filterFn) {
return Object.entries(obj).reduce((a, [key, value]) => (
filterFn(value)
? { ...a, [key]: value }
: a
), {});
},
};
// The imperative way
const objUtils = {
mapProps(obj, mapFn) {
const out = {};
for (const [key, value] of Object.entries(obj)) {
out[key] = mapFn(value);
}
return out;
},
filterProps(obj, filterFn) {
const out = {};
for (const [key, value] of Object.entries(obj)) {
if (filterFn(value)) {
out[key] = value;
}
}
return out;
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment