Skip to content

Instantly share code, notes, and snippets.

@khalidahmada
Last active July 3, 2019 08:32
Show Gist options
  • Save khalidahmada/df3c9ab0d2fc2d744c73e725d3ff9f9b to your computer and use it in GitHub Desktop.
Save khalidahmada/df3c9ab0d2fc2d744c73e725d3ff9f9b to your computer and use it in GitHub Desktop.
Lodash get with optional expression
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);
@khalidahmada
Copy link
Author

Please note that this function is dependency of get lodash and it add the feature of optional values of an object

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment