在JavaScript中,我有一个对象数组:
var allAliases = [
{ "name": "Cards", "alias": "cards", "view": "/path/cards/" },
{ "name": "Carousel", "alias": "carousel", "view": "/path/carousel/" },
{ "name": "Image boxes", "alias": "imageBoxes", "view": "/path/imageBoxes/" },
{ "name": "Gallery", "alias": "gallery", "view": "/path/gallery/" },
{ "name": "Slide panels", "alias": "slidePanels", "view": "/path/slide-panels/" }
]
然后我会有一个别名的字符串数组,如下所示:
var aliases = 'cards,carousel,gallery';
var permittedAliases = aliases.split(',');
我需要过滤原始数组,以便仅剩下别名值与permittedAliases
数组中的字符串匹配的对象。因此,在上述情况下,我将被留下:
[
{ "name": "Cards", "alias": "cards", "view": "/path/cards/" },
{ "name": "Carousel", "alias": "carousel", "view": "/path/carousel/" },
{ "name": "Gallery", "alias": "gallery", "view": "/path/gallery/" }
]
我可以这样创建一个新数组,遍历原始数组,比较值,然后将匹配的对象添加到新数组中,如下所示:
var filteredArray = [];
for (var i = 0; i < allAliases.length; i++) {
for (j = 0; j < permittedAliases.length; j++) {
if (allAliases[i].alias === permittedAliases[j]) {
filteredArray.push(allAliases[i]);
}
}
}
尽管这让我感觉很笨拙,但在循环中循环。我想知道是否有更整洁的方法?
不幸的是,它必须为 ES5.1 。
非常感谢。
答案 0 :(得分:1)
您可以使用Array#filter
和Array#some
作为别名来过滤数组。
var allAliases = [{ "name": "Cards", "alias": "cards", "view": "/path/cards/" }, { "name": "Carousel", "alias": "carousel", "view": "/path/carousel/" }, { "name": "Image boxes", "alias": "imageBoxes", "view": "/path/imageBoxes/" }, { "name": "Gallery", "alias": "gallery", "view": "/path/gallery/" }, { "name": "Slide panels", "alias": "slidePanels", "view": "/path/slide-panels/" }],
aliases = 'cards,carousel,gallery',
permittedAliases = aliases.split(','),
filtered = allAliases.filter(function (o) {
return permittedAliases.some(function (a) {
return o.alias === a;
});
});
console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }
或者您可以使用Array#indexOf
代替Array#some
var allAliases = [{ "name": "Cards", "alias": "cards", "view": "/path/cards/" }, { "name": "Carousel", "alias": "carousel", "view": "/path/carousel/" }, { "name": "Image boxes", "alias": "imageBoxes", "view": "/path/imageBoxes/" }, { "name": "Gallery", "alias": "gallery", "view": "/path/gallery/" }, { "name": "Slide panels", "alias": "slidePanels", "view": "/path/slide-panels/" }],
aliases = 'cards,carousel,gallery',
permittedAliases = aliases.split(','),
filtered = allAliases.filter(function (o) {
return permittedAliases.indexOf(o.alias) !== -1;
});
console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }