所以我有一个包含两个不同数组的数组:
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"]));
假设我只想获得“dir”数组,其中文件夹的名称是“somefolder”。
所以我不想要这样的smth,因为......:
return _staticRoutingTable.forEach(function callb(route) {
return route.dir.filter(function callb(directory) {directory=="somefolder" })
});
....我得到了dir + extention数组。我怎样才能过滤一个数组(在本例中为“dir”)。
答案 0 :(得分:0)
我仍然不确定我是否正确理解了您的问题 - 但要获得像['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); });