Skip to content

Instantly share code, notes, and snippets.

@ancms2600
Created May 31, 2018 16:16
Show Gist options
  • Save ancms2600/28532d6a5fcf9c1412dce38897264d92 to your computer and use it in GitHub Desktop.
Save ancms2600/28532d6a5fcf9c1412dce38897264d92 to your computer and use it in GitHub Desktop.
Case-insensitive Lodash-esque _.get() and _.unset()
// like lodash _.get() but key lookup is case-insensitive
const iget = (value, prop, defaultValue) => {
if (_.isPlainObject(value)) {
if (_.isString(prop) && prop !== '') {
return iget(value, prop.split('.'), defaultValue);
} else if (_.isArray(prop) && prop.length) {
const key = _.toLower(prop.shift()),
val = Object.keys(value).reduce((a, k) => {
if (a !== undefined) {
return a;
}
if (_.toLower(k) === key) {
return value[k];
}
}, undefined);
if (prop.length) {
let v = iget(val, prop, defaultValue);
return v === undefined ? defaultValue : v;
}
return val === undefined ? defaultValue : val;
}
}
return defaultValue;
};
// like lodash _.unset() but key lookup is case-insensitive
const iunset = (value, prop) => {
if (_.isPlainObject(value)) {
if (_.isString(prop) && prop !== '') {
iunset(value, prop.split('.'));
} else if (_.isArray(prop) && prop.length) {
const key = _.toLower(prop.shift()),
val = Object.keys(value).reduce((a, k) => {
if (a !== undefined) {
return a;
}
if (_.toLower(k) === key) {
if (0 === prop.length) {
delete value[k];
}
else {
return value[k];
}
}
}, undefined);
if (prop.length) iunset(val, prop);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment