get-obj-deep-prop

Check and get object prop.

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
get-obj-deep-prop
1.2.14 years ago4 years agoMinified + gzip package size for get-obj-deep-prop in KB

Readme

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"