DEV Community

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

Collapse
 
aminnairi profile image
Amin • Edited

Shouldn't it be:

_.get(obj, "user.pets[0].toys[0].price");

Instead of:

_.get(obj, 'obj.user.pets[0].toys[0].price');

?

Plus, you don't want to import the whole 69kb of Lodash just for this matter. Since you are using ECMAScript Modules, you should use named imports instead.

import { get } from "lodash";

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

console.log(get(obj, "user.pets[0].toys[0].price"));
// 1999

Niftier, and does not import the unnecessary functions just to use the get helper.