Underscore.js findWhere嵌套对象 [英] Underscore.js findWhere nested objects

查看:73
本文介绍了Underscore.js findWhere嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的文件夹/文件对象:

I have an object of folders/files that looks like this:

{
  about.html : {
    path : './about.html'
  },
  about2.html : {
    path : './about2.html'
  },
  about3.html : {
    path : './about3.html'
  },
  folderName : {
    path : './folderName',
    children : {
      sub-child.html : {
        path : 'folderName/sub-child.html'
      }
    }
  }
}

它可以深入6-7层有孩子的文件夹中.

And it can go 6-7 levels deep of folders having children.

我想找到 path 等于我提供的字符串的对象.不管它有多深.

I want to find the object where path is equal to a string that I provide. Regardless of how deep it is.

我使用的下划线仅是顶级的:

I'm using underscore which only does top level:

_.findWhere(files,{path:'./about2.html'}

如何进行深入的嵌套搜索.下划线对此有帮助吗,还是我需要使用递归构建一个mixin?

How can I do a deep, nested search. Does underscore have something for this or do I need to build a mixin with recursion?

推荐答案

这不是最漂亮的代码,但我对其进行了测试,它似乎可以按照您的要求工作.它设置为lodash/下划线混合,但是可以使用.用法如下:

This isn't the prettiest code, but I tested it out and it seems to work the way you are asking. It's setup as a lodash/underscore mixin, but can be used however. Usage would be like this:

_.findDeep(testItem, { 'path': 'folderName/sub-child.html' })

实施:

findDeep: function(items, attrs) {

  function match(value) {
    for (var key in attrs) {
      if(!_.isUndefined(value)) {
        if (attrs[key] !== value[key]) {
          return false;
        }
      }
    }

    return true;
  }

  function traverse(value) {
    var result;

    _.forEach(value, function (val) {
      if (match(val)) {
        result = val;
        return false;
      }

      if (_.isObject(val) || _.isArray(val)) {
        result = traverse(val);
      }

      if (result) {
        return false;
      }
    });

    return result;
  }

  return traverse(items);

}

这篇关于Underscore.js findWhere嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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