Proposal: Object.path([ ... ], defaultValue)

# Vikash Agrawal (6 years ago)

Hello Everyone,

It is a lot of times that we see x is not a property of undefined and to solve this we have to resort to &&, something like -> data &&

data.childData && data.childData.innerDataArray && data.childData.innerDataArray.length

0 whiich is quiet verbose.

I suggest, we should add a utility method like Object.path, which takes an array of strings and returns the value from a given nested object. Also, this can take a second argument which will be a default value if not found.

This is inspired by path and pathOr as implemented in ramdajs.com/docs/#path

~Vikash

# Sebastian Malton (6 years ago)

An HTML attachment was scrubbed... URL: esdiscuss/attachments/20180215/302a6ad6/attachment-0001

# Vikash Agrawal (6 years ago)

Sure Sebastian.

# Andrea Giammarchi (6 years ago)

?. does not compose though, and a standard way to retrieve a path is needed in JSON Pointer too [1]

I've personally used similar approach in various cases, and old libraries like Ext.JS used to Function("this." + path.join('.')).call(target) to retrieve a path in a speedy way.

Beside the "array of string" bit, which is limited if we think nested Arrays and/or Symbols as properties, I think a standard way to retrieve a path would be beneficial in various cases.

Just my 2 cents.

[1] tools.ietf.org/html/rfc6901

# Jordan Harband (6 years ago)

Seems like it composes fine (using ??./??[ syntax): `function retrieve(obj, path) { return path.split('.').reduce((prev, key) =>

prev??[key], obj); } retrieve(someObject, 'a.b.c.d')`

# Naveen Chawla (6 years ago)

Of course you can compose paths with it (and even without it), but it doesn't compose on it's own like a standard path syntax could.