1.2.1 • Published 3 years ago

lodash-plus v1.2.1

Weekly downloads
173
License
MIT
Repository
-
Last release
3 years ago

Lodash Plus

This aims to add deep properties check to common lodash functions. The idea is to avoid annoying multiple checks to access a given node in an object. With lodash-plus, you can specify the path to the property you want as a string :

_.isStringDeep(obj, 'prop.deepProp.reallyDeepProp.wantedPropValue');

This will check whether wantedPropValue inside obj is a String or not.

The following functions are available :

  • filterDeep
  • findDeep
  • findLastDeep
  • hasOwnPropertyDeep
  • isArrayDeep
  • isBooleanDeep
  • isFunctionDeep
  • isNumberDeep
  • isObjectDeep
  • isStringDeep

Usage :

With NodeJS

$ npm install lodash lodash-plus
var _ = require('lodash');

require('lodash-plus')(_);

console.log(_.isStringDeep({a : { b : 'foo' }}, 'a.b'));

Inside a browser

$ bower install lodash lodash-plus
<script src="path/to/lodash.js"></script>
<script src="path/to/lodashPlus.js"></script>
<script>
    console.log(_.isStringDeep({a : { b : 'foo' }}, 'a.b'));
</script>

Exemples :

var testObj = {a : {b : {c : {d : [{e : {f : [{g : true}]}}]}}}},
    testTab = [{a : {b : 1}}, {a : {b : 2}}, {a : {b : 2, c : 3}}, {a : 1}, {c :2}];

console.log(_.isArrayDeep(testObj, 'a.b.c.d')); // true

console.log(_.isStringDeep(testObj, 'a.b.c.d[0].e.f[0].g')); // false
console.log(_.isBooleanDeep(testObj, 'a.b.c.d[0].e.f[0].g')); // true

console.log(_.hasOwnPropertyDeep(testObj, 'a.b.c')); // true
console.log(_.hasOwnPropertyDeep(testObj, 'a.e')); // false

console.log(_.findDeep(testTab, 'a.b')); // testTab[0]
console.log(_.findDeep(testTab, 'a.b', function (item) {
  return item.a.b === 2; // We can access item.a.b safely.
})); // testTab[1]

console.log(_.findLastDeep(testTab, 'a.b', function (item) {
  return item.a.b === 2;
})); // testTab[2]

console.log(_.filterDeep(testTab, 'a.b')); // [testTab[0], testTab[1], testTab[2]]
console.log(_.filterDeep(testTab, 'a.b', function(item) {
  return item.a.b === 2;
})); // [testTab[1], testTab[2]]

// These new functions can be chained too :
console.log(_(testTab)
  .chain()
  .filterDeep('a.b', function(item) {
    return item.a.b === 2;
  })
  .reduce(function(memo, item) {
    return memo += item.a.b;
  }, 0)
  .value()); // 4

Tests

You can run the tests by typing npm test

Contributors