[英]Most performant way to crawl json object array
I've got a list with ~1000 possible file extensions and it's aliases. 我有一个列表,列出了〜1000个可能的文件扩展名,它是别名。 The structure looks like this:
结构如下:
var iconMap = [
{ icon: 'photoshop', extensions: ['psd'], format: 'svg' },
{ icon: 'photoshop2', extensions: ['psd'], format: 'svg', disabled: true },
{ icon: 'php', extensions: ['php1', 'php2', 'php3', 'php4', 'php5', 'php6', 'phps', 'phpsa', 'phpt', 'phtml', 'phar'], format: 'svg' }]
I want to get the 'icon' property for the according extension. 我想获取相应扩展名的'icon'属性。 Therefore I want to create a
getExtensionIcon(fileExtension)
function which should return: 因此,我想创建一个
getExtensionIcon(fileExtension)
函数,该函数应返回:
var phpIcon = getExtensionIcon('php') // 'php'
var pharIcon = getExtensionIcon('phar') // 'php'
var php5Icon = getExtensionIcon('php5') // 'php'
My question: 我的问题:
I only got a few ideas which would be very ineffecient, so I am curious how you would realize the getExtensionicon function? 我只得到了一些效率很低的想法,所以我很好奇您将如何实现getExtensionicon函数?
Here is how I would do it - this "pre-processes" the iconMap once, creating an object that keys extension
with a value of icon
这是我的操作方法-一次“预处理” iconMap,创建一个对象,该对象使用
icon
的值来extension
var iconMap = [ { icon: 'photoshop', extensions: ['psd'], format: 'svg' }, { icon: 'photoshop2', extensions: ['psd'], format: 'svg', disabled: true }, { icon: 'php', extensions: ['php1', 'php2', 'php3', 'php4', 'php5', 'php6', 'phps', 'phpsa', 'phpt', 'phtml', 'phar'], format: 'svg' } ]; var getExtensionIcon = (src => { var extensions = src.filter(item => !item.disabled).reduce((result, item) => { item.extensions.forEach(ext => { result[ext] = item.icon; }); return result; }, {}); return ext => extensions[ext]; })(iconMap); console.log('psd is', getExtensionIcon('psd')); console.log('php1 is', getExtensionIcon('php1'));
If you can use jQuery, it has the $.grep()
function which seems like a good fit for this purpose: 如果可以使用jQuery,则它具有
$.grep()
函数,似乎很适合此目的:
function getExtensionIcon(arr, lang){
var result = $.grep(arr, function(e){ return e.extensions.indexOf(lang) != -1; });
return result[0].icon;
}
I don't really know how performant this is, but you should at least give it a try ;) 我真的不知道它的表现如何,但是您至少应该尝试一下;)
Testing with your Example: 用您的示例进行测试:
function getExtensionIcon(arr, lang){ var result = $.grep(arr, function(e){ return e.extensions.indexOf(lang) != -1; }); return result[0].icon; } var iconMap = [ { icon: 'photoshop', extensions: ['psd'], format: 'svg' }, { icon: 'photoshop2', extensions: ['psd'], format: 'svg', disabled: true }, { icon: 'php', extensions: ['php1', 'php2', 'php3', 'php4', 'php5', 'php6', 'phps', 'phpsa', 'phpt', 'phtml', 'phar'], format: 'svg' }]; console.log(getExtensionIcon(iconMap, "php6"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.