0.1.1 • Published 10 years ago

getpath v0.1.1

Weekly downloads
2
License
WTFPL
Repository
github
Last release
10 years ago

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!

0.1.1

10 years ago

0.1.0

10 years ago

0.0.2

10 years ago

0.0.1

10 years ago