DEV Community

Discussion on: No Optional Chaining? No Problem. Write Your Own deepGet Function!

Collapse
 
starpebble profile image
starpebble

Here is an alternative with JSONPath Expressions, a tool for selecting data in a JSON structure by an expression kinda like XPath does for XML. Here is an expression example: "$.user.pets[0].toys[0].price" - to select the price for the first toy for the first pet for the user. A JavaScript object is a perfect fit for a JSONPath expression evaluation where the object contains nested arrays, dictionaries, and strings.

const {JSONPath} = require('jsonpath-plus');

const obj = {
  user: {
    name: "Joe",
    age: 20,
    pets: [
      {
        name: "Daffodil",
        type: "dog",
        toys: [
          {
            name: "Toughy",
            price: 1999
          }
        ]
      }
    ]
  }
};

console.log(JSONPath({path: '$.user.pets[0].toys[0].price', json: obj, wrap: false}));
// 1999

console.log(JSONPath({path: '$.user.dogs[0].toys[0].price', json: obj, wrap: false}));
// undefined

The npm package jsonpath-plus is a popular JSON Path evaluation engine though pick any one in the world you like! JSONPath probably wasn't invented by a computer. It's very user friendly.

lodash .get() is my second most favorite alternative. Kinda looks like some of use of lodash is going to get deleted when we all can use optional chaining. Which isn't a bad thing.