Does the object have a path
npm i jrf-path-exists
Get the value of an object along the path.
If the path does not exist, then undefined
or the default value
will be returned.
pathExists(obj, path, defaultValue);
const user = response && response.data && response.data.nodes && response.data.nodes[0] && response.data.nodes[0].builds && response.data.nodes[0].builds[0] && response.data.nodes[0].builds[0].user;
const user = pathExists(response, 'response.data.nodes[0].builds[0].user');
let user = response && response.data && response.data.nodes && response.data.nodes[0] && response.data.nodes[0].builds && response.data.nodes[0].builds[0] && response.data.nodes[0].builds[0].user;
user = user || {username: ''};
const user = pathExists(response, 'response.data.nodes[0].builds[0].user', {username: ''});
const pathExists = require('jrf-path-exists');
const obj = {
a: {
b: {
c: 'hello world'
}
},
d: {
arr: ['hello', 'world', {a: 8, b: ['one', 'two', 'three']}, ['q', 'w', 'r', ['h', 'l', 'o']]]
},
e: ['one el', 'two el']
};
const b = 'b';
console.log(pathExists(obj, 'a.b.c', null));
console.log(pathExists(obj, `a[${b}].c`));
console.log(pathExists(obj, `a.${b}.c`));
console.log(pathExists(obj, 'a.b.c.d.s'));
console.log(pathExists(obj, 'd.arr[2].b[1]'));
console.log(pathExists(obj, 'd.arr[3].3.2'));
console.log(pathExists(obj, 'd.arr[3][3][2]'));
console.log(pathExists(obj, 'e[1]'));
console.log(pathExists(obj, 'e[4]'));
console.log(pathExists(obj, 'e[4]', null));
console.log(pathExists(obj, 'e[4]', false));
console.log(pathExists(obj, 'e[4]', 0));
console.log(pathExists(obj, 'e[4]', []));
console.log(pathExists(obj, 'e[4]', ''));
console.log(pathExists(obj, 'e[4]', {}));