Skip to content

Instantly share code, notes, and snippets.

@jeneg
Last active December 21, 2023 17:00
Show Gist options
  • Star 34 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jeneg/9767afdcca45601ea44930ea03e0febf to your computer and use it in GitHub Desktop.
Save jeneg/9767afdcca45601ea44930ea03e0febf to your computer and use it in GitHub Desktop.
Alternative to lodash get method _.get()
function get(obj, path, def) {
var fullPath = path
.replace(/\[/g, '.')
.replace(/]/g, '')
.split('.')
.filter(Boolean);
return fullPath.every(everyFunc) ? obj : def;
function everyFunc(step) {
return !(step && (obj = obj[step]) === undefined);
}
}
@SupremeTechnopriest
Copy link

@JamesGardnerKT

If you knew the depth you could do something like:

const obj = {
  a: {
    b: {
      c: 1
    }
  }
}

const path = 'a.b.c'
const fallback = 2
const parts = path.split('.')

const value = obj[parts[0]]?.[parts[1]]?.[parts[2]] ?? fallback
console.log(value) // 1

If you don't know the depth, I think the get method is going to be the best route. You could check the length of parts and do a switch and handle all possible depths, but Im not sure if thats going to out perform the get methods above.

@SupremeTechnopriest
Copy link

Maybe I will maintain a benchmark for this problem.

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