get-obj-deep-prop

1.2.1 • Public • Published

Get Object Deep Prop

Check and get object prop.

Install

npm install get-obj-deep-prop
yarn add get-obj-deep-prop

Usage

Schema

getObjDeepProp([ object, [ props, [ defaultValue]])

Example

import getObjDeepProp from "get-obj-deep-prop";
const userObj = {
  user: {
    username: "John",
    information: {
      firstname: "John",
      lastname: "Doe",
      social: {
        facebook: "johhnn",
        twitter: "jhnn"
      }
    }
  }
};
const userFacebookUsername = getObjDeepProp(
  userObj,
  "user.information.social.facebook"
);

console.log(userFacebookUsername); // "johhnn"

Why should I use

Because you might have to check.

const userObj = {
  user: {
    username: "John",
    information: {
      firstname: "John",
      lastname: "Doe"
    }
  }
};
const userFacebookUsername = userObj.user.information.social.facebook;
// Uncaught TypeError: Cannot read property 'facebook' of undefined
// ↓ This code doesn't work ↓
console.log(userFacebookUsername);

You have to do

let userFacebookUsername;
if (
  userObj &&
  userObj.user &&
  userObj.user.information &&
  userObj.user.information.social &&
  userObj.user.information.social.facebook
) {
  userFacebookUsername = userObj.user.information.social.facebook;
}

console.log(userFacebookUsername); // undefined

If you use getObjDeepProp

No errors, false returns, and the code continues to run.

const userFacebookUsername = getObjDeepProp(
  userObj,
  "user.information.social.facebook"
);
console.log(userFacebookUsername); // false

Default Value

const userFacebookUsername = getObjDeepProp(
  userObj,
  "user.information.social.facebook",
  "Anonim"
);
console.log(userFacebookUsername); // "Anonim"

Package Sidebar

Install

npm i get-obj-deep-prop

Weekly Downloads

130

Version

1.2.1

License

ISC

Unpacked Size

3.46 kB

Total Files

4

Last publish

Collaborators

  • aykutkardas