从重复数组填充数组

时间:2018-08-31 05:51:57

标签: javascript arrays

我正在制作一个用于处理网站翻译的小工具。我已经使这段代码起作用了,但是我觉得使用数组方法应该有一些更优雅,更易读的方式(我的看起来很烂……)。

基本上,我将以代码中显示的格式获取输入(data_import,这只是用于测试的伪数据)。它具有4列[translationTag,uniqueId,languageId,translation]。每种语言的行顺序相同,每种语言的行数相同。语言数量可能会从2种以上更改。

所需的输出如下:

const data_import =  [

  ['aaa', {id:1, langId:1, finnish:'tuntematon'}, {id:5, langId:4, english:'unknown'}, {id:9, langId:6, swedish:'okänd'}],
  ['bbb', {id:2, langId:1, finnish:'auto'}, {id:6, langId:4, english:'car'}, {id:10, langId:6, swedish:'bil'}],
  ['ccc', {id:3, langId:1, finnish:'polkupyörä'}, {id:7, langId:4, english:'bicycle'}, {id:11, langId:6, swedish:'cykel'}],
  ['ddd', {id:4, langId:1, finnish:'rullalauta'}, , {id:8, langId:4, english:'skateboard'}, {id:12, langId:6, swedish:'skateboard'}]
];

这是我的代码“有效”,但丑陋且不可读...

export const language = ['Finnish', 'Estonia', 'Polish', 'English', 'Spanish', 'Swedish'];

const data_import =  [
  ['aaa', 1, 1, 'tuntematon'],
  ['bbb', 2, 1, 'auto'],
  ['ccc', 3, 1, 'polkupyörä'],
  ['ddd', 4, 1, 'rullalauta'],
  ['aaa', 5, 4, 'unknown'],
  ['bbb', 6, 4, 'car'],
  ['ccc', 7, 4, 'bicycle'],
  ['ddd', 8, 4, 'skateboard'],
  ['aaa', 9, 6, 'okänd'],
  ['bbb', 10, 6, 'bil'],
  ['ccc', 11, 6, 'cykel'],
  ['ddd', 12, 6, 'skateboard']];

export const data = process_test(data_import);

function process_test(data) {  
  const numberOfCols = data[0].length;
  const idIndex = numberOfCols - 2;
  const arr_result = []
  let rowMax = 0;
  let rowMaxMulti = 0;
  let langIdLast = 0;
  data.forEach((row, index) => {
    // if = add non-language cols and first language column
    if(row[idIndex] === data[0][idIndex]) {
      rowMax = index + 1;
      const transItem = row.slice(0, idIndex-1);
      transItem.push({ id:row[idIndex], langId:row[idIndex], [language[row[idIndex] - 1]]:row[idIndex + 1] });
      arr_result[index] = transItem;
      langIdLast = row[idIndex];
    }
    // add other languages to datarow
    else {
      const transItem = { id:row[idIndex - 1], langId:row[idIndex], [language[row[idIndex] + 1]]:row[idIndex + 1] };
      if(langIdLast !== row[idIndex]) rowMaxMulti++;
      arr_result[index - rowMax * rowMaxMulti].push(transItem);
      langIdLast = row[idIndex];
    }
  })
  return(arr_result);
}

3 个答案:

答案 0 :(得分:2)

reduce转换为由翻译标签索引的对象,然后获取该对象的值会更简单。在每次迭代中,为累加器中不存在的转换标签创建一个数组。从当前项目的langId中识别语言名称,并将push的新对象命名为数组:

const language = ['Finnish', 'Estonia', 'Polish', 'English', 'Spanish', 'Swedish'];

const data_import =  [
  ['aaa', 1, 1, 'tuntematon'],
  ['bbb', 2, 1, 'auto'],
  ['ccc', 3, 1, 'polkupyörä'],
  ['ddd', 4, 1, 'rullalauta'],
  ['aaa', 5, 4, 'unknown'],
  ['bbb', 6, 4, 'car'],
  ['ccc', 7, 4, 'bicycle'],
  ['ddd', 8, 4, 'skateboard'],
  ['aaa', 9, 6, 'okänd'],
  ['bbb', 10, 6, 'bil'],
  ['ccc', 11, 6, 'cykel'],
  ['ddd', 12, 6, 'skateboard']];

const data = Object.values(data_import.reduce((a, [tTag, id, langId, word]) => {
  if (!a[tTag]) a[tTag] = [tTag];
  const langName = language[langId - 1];
  a[tTag].push({ id, langId, [langName]: word });
  return a;
}, {}));
console.log(data);

答案 1 :(得分:1)

您可以通过tagArray.prototype.reduce对数据进行分组,并使用Object.keys将数据映射到所需的格式

const language = ['Finnish', 'Estonia', 'Polish', 'English', 'Spanish', 'Swedish'];

const data_import = [['aaa', 1, 1, 'tuntematon'],['bbb', 2, 1, 'auto'],['ccc', 3, 1, 'polkupyörä'],['ddd', 4, 1, 'rullalauta'],['aaa', 5, 4, 'unknown'],['bbb', 6, 4, 'car'],['ccc', 7, 4, 'bicycle'],['ddd', 8, 4, 'skateboard'],['aaa', 9, 6, 'okänd'],['bbb', 10, 6, 'bil'],['ccc', 11, 6, 'cykel'],['ddd', 12, 6, 'skateboard']];

const grouped = data_import.reduce((all, [tag, id, langId, tran]) => {
  
  if (!all.hasOwnProperty(tag)) all[tag] = [];

  all[tag].push({id, langId, [language[langId-1]]: tran});

  return all;

}, {});

const result = Object.keys(grouped).map(tag => [tag, ...grouped[tag]]);

console.log(result);

答案 2 :(得分:0)

您也可以使用

  1. Array.prototype.map()
  2. Array.prototype.filter()
  3. new Set([])
  4. destructuring assignment

const data_import = [["aaa",1,1,"tuntematon"],["aaa",5,4,"unknown"],["aaa",9,6,"okänd"],["bbb",6,4,"car"],["bbb",2,1,"auto"],["bbb",10,6,"bil"],["ccc",11,6,"cykel"],["ccc",7,4,"bicycle"],["ccc",3,1,"polkupyörä"],["ddd",8,4,"skateboard"],["ddd",4,1,"rullalauta"],["ddd",12,6,"skateboard"]],

      language = ['Finnish', 'Estonia', 'Polish', 'English', 'Spanish', 'Swedish'];

const keys =[...new Set(data_import.map(v => v[0]))];

let result = keys.map(key => [key, data_import.filter(v => v[0] == key).map(v => {
    return {
        id: v[1],
        langId: v[2],
        [language[v[2]-1]]: v[3]
    }
})]);

console.log(result)
.as-console-wrapper {max-height: 100% !important;top: 0;}