下划线相当于Lodash _.get和_.has [英] Underscore equivalent of Lodash _.get and _.has

查看:43
本文介绍了下划线相当于Lodash _.get和_.has的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试搜索与Lodash _.get _.has 等价的Underscore,在这里它可以直接访问嵌套对象的存在和值价值,而无需检查其父母是否存在.

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.

但是,在我看来,在 _.get _.has 下划线只能检查第一级的值.

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

推荐答案

据我所知,undercore不会执行深度搜索,因此您必须适应浅度的 has 获取(或更改为lodash).

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).

您也可以尝试自己实现(可以检查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).

这是对 has 问题( get 类似)的简单解决方案,使用递归和当前下划线 has 的实现

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

希望有帮助.

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>

这篇关于下划线相当于Lodash _.get和_.has的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆