gpt4 book ai didi

javascript - 优化嵌套循环以从数组中过滤包含特定值的对象

转载 作者:行者123 更新时间:2023-11-30 19:52:13 25 4
gpt4 key购买 nike

<分区>

在 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

非常感谢。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com