Socket
Socket
Sign inDemoInstall

getpath

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

getpath

Get the value of a nested object key (including array indexes) if it exists, or undefined if it doesn't, without worrying about checking you still have a value at each level.


Version published
Maintainers
1
Created
Source

getPath

Kinda like isSet from that other language, but you get the value back too.

What

getPath takes an object (or array), and a string representing the path to a key you want to find within it. If it exists you'll get the value back, and if it doesn't you'll just get undefined. When you can't guarantee a value exists within the object this saves you from testing at every level.

In other words,

let myValue = 'default';

if (myObject && myObject.maybe && myObject.maybe[1] && myObject.maybe[1].maybeNot) {
	myValue = myObject.maybe[1].maybeNot;
}

becomes

const myValue = getPath(myObject, 'maybe[1].maybeNot') || 'default';

How

getPath takes two arguments - the object you want to find something within, and the path to what you want as a string. The path can include dot-notation and array indices.

If you have an object called a and want to use the value of a.b[1].c if it exists, just call getPath(a, 'b[1].c'). If that exists, you'll get it, and if any part of that path doesn't exist you'll just get undefined. Easy!

FAQs

Package last updated on 28 Sep 2016

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc