Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

jsdig

devchris156MIT0.1.6

Based on Ruby's hash#dig

javascript, ruby, dig, hash, optional, chaining, safe, navigation

readme

Build

Lightweight Javascript implementation of Ruby's hash#dig (https://apidock.com/ruby/Hash/dig) - no dependencies

How to install it

Via npm

npm install jsdig

Via yarn

yarn add jsdig

After installing, import it in your project with:

import 'jsdig';

OR

require('jsdig');

How to use it

  • 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: '' });
// => ''

License

MIT © Christoph Drechsler