So-called object-path
notation
Nearly a decade ago, Mario Casciaro, the author of Node.js Design Patterns book, published an npm package object-path
.
It’s a getter/setter helper which works on any data structures:
import { get } from "object-path";
const testObj1 = {
foo: {
bar: "value",
},
};
const testObj2 = {};
console.log(get(testObj1, "foo.bar"));
// => "value"
console.log(get(testObj2, "foo.bar"));
// => null
The
optional chaining
is a substitute for get
(provided you put question marks
correct in front of every dot), but there are eight more methods in object-path
which don’t have native JS equivalents.
But object-path
has one peculiar detail — it marks the array paths also using dots, not brackets (as in native JS):
import { get } from "object-path";
const testArr1 = [["value"]];
const testArr2 = [];
console.log(get(testArr1, "0.0"));
// => "value"
console.log(get(testArr2, "0.0"));
// => null
Practically, this dot-based path notation makes the life easier, both
for program authors and program users. Just compare
somePath.split(".").some(...)
with… ahem, whatever the
bracket-aware equivalent would be…
When objects and arrays are nested, we get paths like
foo.1.bar.3.value
(as opposed to native JS foo[1].bar[3].value
).
Many packages our ours use this “dot notation”: