2017-10-11 67 views
0

我有這三個數組:推多個陣列爲對象的有序陣列

const time = ["8n", "8n", "4n", "4n", "8n", "8n"];  
const note = [422, 303, 482, 419, 478, 467, 317, 343];  
const velocity = [0.57, 0.28, 0.35, 0.45, 0, 0.4, 0.53, 0.46, 0.48, 0.39]; 

如何把這些成這樣了,注意匹配指數:

const part = [ 
    { time: "8n", note: 422, velocity: 0.57 }, 
    { time: "8n", note: 303, velocity: 0.28 }, 
    { time: "4n", note: 482, velocity: 0.35 } 
]; 

的期初數組長度時間,音符和速度總是不同的,所以部分長度應該與最初的三個一樣。

任何意見將不勝感激,謝謝。

+2

這不是一個代碼編寫的服務。請發佈您嘗試過的以及發生問題的位置。可能的答案是使用[* Array.prototype.map *](https://tc39.github.io/ecma262/#sec-array.prototype.map)的一行代碼,另一行可能使用[* reduce *]( https://tc39.github.io/ecma262/#sec-array.prototype.reduce)。 – RobG

回答

0

像這樣:

addEventListener('load', function(){ 
 
const time = ["8n", "8n", "4n", "4n", "8n", "8n"];  
 
const note = [422, 303, 482, 419, 478, 467, 317, 343];  
 
const velocity = [0.57, 0.28, 0.35, 0.45, 0, 0.4, 0.53, 0.46, 0.48, 0.39]; 
 
for(var i=0,part=[],l=time.length; i<l; i++){ 
 
    part.push({time:time[i], note:note[i], velocity:velocity[i]}); 
 
} 
 
console.log(part); 
 
});

1

你的意思呢?

const time = ["8n", "8n", "4n", "4n", "8n", "8n"]; 
 
const note = [422, 303, 482, 419, 478, 467, 317, 343]; 
 
const velocity = [0.57, 0.28, 0.35, 0.45, 0, 0.4, 0.53, 0.46, 0.48, 0.39]; 
 

 
const merge = (timeArr, noteArr, velocityArr) => { 
 
    const length = Math.min(time.length, note.length, velocity.length); 
 
    const ret = []; 
 

 
    for (let i = 0; i < length; i++) { 
 
     ret.push({ 
 
      time: timeArr[i], 
 
      note: noteArr[i], 
 
      velocity: velocityArr[i] 
 
     }); 
 
    } 
 

 
    return ret; 
 
}; 
 

 
console.log(merge(time, note, velocity));

+0

這是完美的。謝謝! –

0

您可以在陣列的通緝零件圖。

const time = ["8n", "8n", "4n", "4n", "8n", "8n"]; 
 
const note = [422, 303, 482, 419, 478, 467, 317, 343]; 
 
const velocity = [0.57, 0.28, 0.35, 0.45, 0, 0.4, 0.53, 0.46, 0.48, 0.39]; 
 

 
const merge = (timeArr, noteArr, velocityArr) => timeArr 
 
    .slice(0, Math.min(time.length, note.length, velocity.length)) 
 
    .map((time, i) => ({ 
 
     time, 
 
     note: noteArr[i], 
 
     velocity: velocityArr[i] 
 
    })); 
 

 
console.log(merge(time, note, velocity));
.as-console-wrapper { max-height: 100% !important; top: 0; }