【问题标题】:Filter one Array which is in another array过滤另一个数组中的一个数组
【发布时间】:2017-03-01 14:56:31
【问题描述】:

所以我有一个包含两个不同数组的数组:

 var _staticRoutingTable = [];

 function StaticRoute(directory, extentions) {
        this.dir = directory;
        this.extentions = extentions;
 }

_staticRoutingTable.push(new StaticRoute(["htmlfolder"], ["./html"]));
_staticRoutingTable.push(new StaticRoute(["somefolder"], ["./html","./txt","./css"]));

假设我只想获取文件夹名称为“somefolder”的“dir”数组。

所以我不想这样,因为...:

 return _staticRoutingTable.forEach(function callb(route) {           
       return route.dir.filter(function callb(directory) {directory=="somefolder" })
 });

.... 我得到 dir + 扩展数组。我怎样才能只过滤一个数组(在本例中为“dir”)。

【问题讨论】:

  • 所以你想要完整的 StaticRoute,它有 this.dir == 'somefolder' ?
  • @baao 不,我不希望StaticRoute完整,我只想返回一个数组,其中包含一个名为“somefolder”的字符串(在本例中9

标签: arrays node.js filter


【解决方案1】:

我仍然不确定我是否正确理解了您的问题 - 但要获得像 ['something'] 这样的数组,您可以使用 find:

var _staticRoutingTable = [];

function StaticRoute(directory, extentions) {
    this.dir = directory;
    this.extentions = extentions;
}

_staticRoutingTable.push(new StaticRoute(["htmlfolder"], ["./html"]));
_staticRoutingTable.push(new StaticRoute(["somefolder"], ["./html","./txt","./css"]));

let foo = _staticRoutingTable.find(function (a) {
    return a.dir.indexOf("somefolder") > -1;
});
if (foo) {
    console.log(foo.dir);    
}

请注意,这将只返回第一个匹配项。如果有多个您感兴趣的可能匹配项,您可以切换过滤器以查找并使用结果数组。

但是,当您正在搜索“somefolder”并希望返回像 ['somefolder'] 这样的数组时,这样做会更容易

console.log(['somefolder']);

...

这适用于多个匹配项:

    var _staticRoutingTable = [];

    function StaticRoute(directory, extentions) {
        this.dir = directory;
        this.extentions = extentions;
    }

    _staticRoutingTable.push(new StaticRoute(["htmlfolder"], ["./html"]));
    _staticRoutingTable.push(new StaticRoute(["somefolder"], ["./html","./txt","./css"]));

    let foo = _staticRoutingTable.filter(function (a) {
        return a.dir.indexOf("somefolder") > -1;
    });
    foo.forEach(function (v) { console.log(v.dir); });

【讨论】:

  • 所以这只有在数组只有一个索引值为“somefolder”的情况下才有效?
  • 如我所写,如果有多个,请将 find 替换为 filter @igodie
  • 编辑了答案@igodie
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多