Lightweight Javascript implementation of Ruby's hash#dig (https://apidock.com/ruby/Hash/dig) - no dependencies
Via npm
npm install jsdig
Via yarn
yarn add jsdig
After installing, import it in your project with:
import 'jsdig';
OR
require('jsdig');
- With an Object:
const world = {
locations: {
europe: 'Bamberg',
usa: 'Indianapolis'
}
};
world.dig('locations', 'usa');
// => 'Indianapolis'
- With an Array:
const world = {
locations: [{
europe: 'Bamberg',
}, {
usa: 'Indianapolis'
}]
};
world.dig('locations', 0, 'europe');
// => 'Bamberg'
- It can also call a function inside a nested object, or in an array, or in both:
const germany = () => 'germany';
const world = [0, 1, { location: { europe: germany } }, 3];
world.dig(2, 'location', 'europe') === germany;
world.dig(2, 'location', 'europe')() === 'germany';
- If it can't find the value, it will return null by default. However, you can also pass in a default value of what should be returned if it isn't found.
const world = {
locations: [{
europe: 'Bamberg',
}, {
usa: 'Indianapolis'
}]
};
world.dig('locations', 0, 'europe', 'germany', { default: [] });
// => []
world.dig('locations', 0, 'europe', 'germany', { default: 'not found' });
// => 'not found'
world.dig('locations', 0, 'europe', 'germany', { default: '' });
// => ''
MIT © Christoph Drechsler