ES6將兩個數組合並成一個對象數組


需求

有這么兩個數組

 1 let metrodates = [  2  "2008-01",  3  "2008-02",  4  "2008-03",..ect  5 ];  6 let figures = [  7  0,  8  0.555,  9  0.293,..ect 10 ]

想要這樣的結果

1 let result = [ 2    {data: 0, date: "2008-01"}, 3    {data: 0.555, date: "2008-02"}, 4    {data: 0.293, date: "2008-03"},..ect 5 ];

方案一

1 let result = []; 2 for(let index in metrodates){ 3  result.push({data: figures[index], date: metrodates[index]}); 4 }

此方案為最原始方法,簡單,但過於low

方案二

1 let result = metrodates.map((date,i) => ({date, data: figures[i]}));

此方案使用了ES6中的map,簡潔,但本質還是遍歷,顯得有些low

方案三

1 const zip = ([x,...xs], [y,...ys]) => { 2   if (x === undefined || y === undefined) 3     return []; 4   else
5     return [[x,y], ...zip(xs, ys)]; 6 } 7 let result = zip(metrodates, figures).map(([date, data]) => ({date, data}));

此方案使用了ES6+遞歸,顯得高大上起來了。

方案四

 1 const isEmpty = xs => xs.length === 0;  2 const head = ([x,...xs]) => x;  3 const tail = ([x,...xs]) => xs;  4 const map = (f, ...xxs) => {  5   let loop = (acc, xxs) => {  6     if (xxs.some(isEmpty))  7       return acc;  8     else
 9       return loop([...acc, f(...xxs.map(head))], xxs.map(tail)); 10  }; 11   return loop([], xxs); 12 } 13 let result = map((date, data) => ({date, data}), metrodates, figures);

此方案是方案三的加強版,它能接受多個數組映射成對象數組,威力無比!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM