优化嵌套循环以从数组中过滤包含某些值的对象

时间:2019-01-25 09:47:44

标签: javascript arrays ecmascript-5

在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

非常感谢。

1 个答案:

答案 0 :(得分:1)

您可以使用Array#filterArray#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; }