Skip to content

Instantly share code, notes, and snippets.

Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@andrewchilds
andrewchilds / deepGet.js
Last active January 11, 2023 22:38 — forked from harish2704/lodash.get.js
Simple, standalone, vanilla implementation of lodash.get
// Simple implementation of lodash.get
// Handles arrays, objects, and any nested combination of the two.
// Also handles undefined as a valid value - see test case for details.
// Based on: https://gist.github.com/harish2704/d0ee530e6ee75bad6fd30c98e5ad9dab
export function deepGet(obj, query, defaultVal) {
query = Array.isArray(query) ? query : query.replace(/(\[(\d)\])/g, '.$2').replace(/^\./, '').split('.');
if (!(query[0] in obj)) {
return defaultVal;
}
obj = obj[query[0]];