vin*_*sty 7 javascript underscore.js lodash
我想有搜索下划线等价物Lodash _.get和_.has,它是能够直接访问的存在和嵌套对象价值的价值,而不需要检查其父母的存在.
但是,在我看来,下划线_.get并且_.has只能检查第一级的值.
var object = { 'a': { 'b': 2 } };
_.has(object, 'a.b'); // lodash shows true
_.has(object, 'a.b'); // underscore shows false
Run Code Online (Sandbox Code Playgroud)
据我所知,undercore不执行深层搜索,所以你必须满足于浅has和get(或更改lodash).
您也可以尝试自己实现它(您可以检查lodash的实现并尝试复制它或提出自己的解决方案).
这是一个简单的has问题解决方案(get类似),使用递归和当前下划线has的实现.
希望能帮助到你.
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'));Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8146 次 |
| 最近记录: |