Created
May 31, 2018 16:16
-
-
Save ancms2600/28532d6a5fcf9c1412dce38897264d92 to your computer and use it in GitHub Desktop.
Case-insensitive Lodash-esque _.get() and _.unset()
This file contains 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
// 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