Package Exports
- get-obj-deep-prop
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (get-obj-deep-prop) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
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"