findObjectPaths
Easy to use zero dependency get or find paths in objects to given key('s), value('s) or key/value
combinations. It is meant to interact nicely with lodash to quickly access or test values in objects,
but can be used standalone as well.
Installation
Install via npm
npm install findObjectPaths
Example data (see test-folder)
acmeInc.json
{
"company": {
"name": "ACME INC",
"address": "1st Street, Toontown, TT",
"founded": "December 31st 1969",
"hasStocks": true,
"numberOfEmployees": 2,
"numberOfActors": 3
}
}
Full Source of acmeInc
Basic usage
import { findObjectPaths } from 'findObjectPaths';
class TestMe {
static async main() {
let acmeInc = {};
rawFileContent = fs.readFileSync(p.resolve(__dirname, 'acmeInc.json'), 'utf-8');
acmeInc = JSON.parse(rawFileContent);
let path = findObjectPaths(acmeInc, {key: 'founded'});
path = findObjectPaths(acmeInc, {value: 'December 31st 1969'});
const allPaths: string[] = findObjectPaths(acmeInc, {key: 'actorId'}) as string[];
const ceoPath = findObjectPaths(acmeInc, {key: 'isCEO', value: true});
}
}
TestMe.main();
See more examples implemented in tests-findObjectPaths.
Convenient Methods
- findObjectPathsByKey Find a single or all path(s) matching to a key in an object
- findObjectPathsByValue Find a single or all path(s) to a value in an object.
- findObjectPathsByKeyValue Find a or all path(s) to a key with a given value in an object
Lodash Mixin
findObjectPaths can be used as a lodash mixin.
import _ from '../lib/FindObjectPathsMixin';
.
.
.
const path = _.findObjectPaths(acmeInc, {key: 'numberOfActors'});
path = _.findObjectPaths(acmeInc, {value: 'DVD'});
if (_.has(acmeInc, _.findObjectPaths(acmeInc, {value: 'DVD'}))) {
const dvd = _.get(acmeInc, _.findObjectPaths(acmeInc, {value: 'DVD'}));
}
Tests
Tests can be found in /test
and run by jest. To run the tests call npm test
.