我有原始数组:
[ 'dev/img/sprites/coctail/coc-1.png',
'dev/img/sprites/coctail/coc-2.png',
'dev/img/sprites/coctail/coc-3.png',
'dev/img/sprites/coctail/coc-4.png',
'dev/img/sprites/coctail/coc-5.png',
'dev/img/sprites/social/advan-1.png',
'dev/img/sprites/social/advan-2.png',
'dev/img/sprites/social/advan-3.png',
'dev/img/sprites/social/advan-4.png',
'dev/img/sprites/testSprite1/s19908f1255e3d10,
'dev/img/sprites/testSprite1/shutterstock_106,
'dev/img/sprites/testSprite1/tel.jpg',
'dev/img/sprites/testSprite1/unnamed.png' ]
有必要根据它制作一个对象数组,如下所示:
[ { data:
[ 'dev/img/sprites/coctail/coc-1.png',
'dev/img/sprites/coctail/coc-2.png',
'dev/img/sprites/coctail/coc-3.png',
'dev/img/sprites/coctail/coc-4.png',
'dev/img/sprites/coctail/coc-5.png' ],
fileName: 'coctail',
destPath: 'app/img/' },
{ data:
[ 'dev/img/sprites/social/advan-1.png',
'dev/img/sprites/social/advan-2.png',
'dev/img/sprites/social/advan-3.png',
'dev/img/sprites/social/advan-4.png' ],
fileName: 'social',
destPath: 'app/img/' },
{ data:
[ 'dev/img/sprites/testSprite1/s19908f1255e3d106eca5d.jpg',
'dev/img/sprites/testSprite1/shutterstock_106748483-247x180.jpg',
'dev/img/sprites/testSprite1/tel.jpg',
'dev/img/sprites/testSprite1/unnamed.png' ],
fileName: 'testSprite1',
destPath: 'app/img/' } ]
原则上,任务已经解决,但我自己并不喜欢我写的代码。结果是很多循环,而且不知何故很麻烦。
任何人都可以看一下并指出可以更紧凑地完成的地方吗?
var fileNames = new Set();
var files = [];
var destination = new Set();
//console.log(matches)
matches.forEach((item, i, arr) => {
if (item.includes(config.spritesFolder)) {
var pos = item.indexOf(config.spritesFolder);
var start = item.indexOf('/', pos) + 1;
var end = item.indexOf('/', start);
fileNames.add(item.slice(start, end));
destination.add(item.slice(0, pos));
}
});
var i = 0;
fileNames.forEach((item, it, arr) => {
files[i] = {};
files[i].data = [];
files[i].fileName = item;
for (var j = 0; j < matches.length; j++) {
if (matches[j].indexOf(item) != -1) {
files[i].data.push(matches[j]);
}
}
i++;
});
for (var i = 0; i < files.length; i++) {
files[i].destPath = '';
destination.forEach((item, it, arr) => {
if (files[i].data[0].indexOf(item) != -1) {
files[i].destPath = item.replace(config.path.src.dir, config.path.build.dir);
}
});
}
console.dir(files)
想了想,我改写了代码如下:
我决定直接在匹配循环中的文件数组中创建对象,并使用一个附加函数来创建这些对象的必要属性。