Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore equivalent of Lodash _.get and _.has

I am trying to have search for Underscore equivalent for Lodash _.get and _.has, where it is able to directly access the existence and value of nested object value without the need of checking the existence of its parents.

However, it seems to me that underscore _.get and _.has only able to check the value for the first level.

var object = { 'a': { 'b': 2 } };
_.has(object, 'a.b'); // lodash shows true
_.has(object, 'a.b'); // underscore shows false
like image 484
vincentsty Avatar asked Feb 04 '17 15:02

vincentsty


People also ask

What is use of _ in Lodash?

js . Lodash helps programmers write more concise and easier to maintain JavaScript code. Lodash contains tools to simplify programming with strings, numbers, arrays, functions and objects. By convention, Lodash module is mapped to the underscore character.

What is _ get?

The _. get() function is an inbuilt function in the Underscore. js library of JavaScript which is used to get the value at the path of object. If the resolved value is undefined, the defaultValue is returned in its place. Syntax: _.get(object, path, [defaultValue])

What is _ has in JavaScript?

The _.has() function is used to check whether the given object contains the given key or not.


1 Answers

As far as I know, undercore doesn't perform a deep search, so you'll have to settle for shallow has and get (or change to lodash).

You can also try to implement it yourself (you can check lodash's implementation and try to copy it or come up with your own solution).

This is a simple solution to the has problem (get would be similar), using recursion and the current underscore has's implementation.

Hope it helps.

var a = {
  a: 1,
  b: {
    a: { c: { d: 1 }}
  }
};

var hasDeep = function(obj, path) {
  if(!path) return true;
  
  var paths = path.split('.'),
    nPath = _.first(paths);
  return _.has(obj, nPath) && hasDeep(obj[nPath], _.rest(paths).join('.'));
}

console.log(hasDeep(a, 'b.a.c.d'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
like image 133
acontell Avatar answered Oct 19 '22 22:10

acontell