Skip to content

aykutkardas/get-obj-deep-prop

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 

Repository files navigation

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"

About

Check and get object prop.

Resources

Stars

Watchers

Forks