Last active
July 3, 2019 08:32
-
-
Save khalidahmada/df3c9ab0d2fc2d744c73e725d3ff9f9b to your computer and use it in GitHub Desktop.
Lodash get with optional expression
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
import { get } from "lodash"; | |
function __get(obj, val, def) { | |
const items = val.split("|"); | |
if (!items.length) return _.get(obj, val, def); | |
const tpl = items.shift(); | |
let value; | |
let index = 0; | |
while (!value && index < items.length) { | |
value = get(obj, `${tpl}.${items[index]}`); | |
index++; | |
} | |
if (!value) value = def; | |
return value; | |
} | |
const obj = { | |
a: { | |
b: { | |
c: "value of c", | |
d: "value of d" | |
}, | |
l:[ | |
"fifo", | |
"tuto" | |
] | |
} | |
}; | |
// example of get with optional values e,x,d,c | |
// the output in this example will be "value of d" | |
// IMPORTANT the optional expression should be in the last string object | |
const val = __get(obj, "a.b|e|x|d|c"); | |
console.log(val); | |
// Example of Array | |
const arr = __get(obj, "a|l[3]|l[1]"); | |
// Output will be tuto | |
console.log(arr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please note that this function is dependency of
get
lodash
and it add the feature of optional values of an object