2016-09-26 162 views
2

我有我想要合併到一起,以一個對象數組兩個數組的數組...ES6:合併兩個數組爲對象

第一個數組是日期(字符串):

let metrodates = [ 
"2008-01", 
"2008-02", 
"2008-03",..ect 
]; 

第二個數組是一個數字:

let figures = [ 
0, 
0.555, 
0.293,..ect 
] 

我想合併他們作出這樣的對象(所以數組項由他們相似的指數匹配):

let metrodata = [ 
    {data: 0, date: "2008-01"}, 
    {data: 0.555, date: "2008-02"}, 
    {data: 0.293, date: "2008-03"},..ect 
]; 

到目前爲止,我這樣做是這樣的:我創建一個空數組,然後通過前兩個數組中的一個循環來獲取索引號(前兩個數組長度相同)...但是在那裏一個更簡單的方法(在ES6中)?

let metrodata = []; 

    for(let index in metrodates){ 
    metrodata.push({data: figures[index], date: metrodates[index]}); 
    } 
+0

[不要在列表中使用'in'枚舉!](http://stackoverflow.com/q/500504/1048572) – Bergi

回答

4

最簡單的方法可能是使用map並提供給回調

let metrodates = [ 
 
    "2008-01", 
 
    "2008-02", 
 
    "2008-03" 
 
]; 
 

 
let figures = [ 
 
    0, 
 
    0.555, 
 
    0.293 
 
]; 
 

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

 
console.log(output);


另一種選擇是讓通用拉鍊功能的指數,將你的兩個輸入數組整理成一個數組。這通常稱爲「拉鍊」,因爲它可以像拉鍊上的牙齒一樣交織輸入。

const zip = ([x,...xs], [y,...ys]) => { 
 
    if (x === undefined || y === undefined) 
 
    return []; 
 
    else 
 
    return [[x,y], ...zip(xs, ys)]; 
 
} 
 

 
let metrodates = [ 
 
    "2008-01", 
 
    "2008-02", 
 
    "2008-03" 
 
]; 
 

 
let figures = [ 
 
    0, 
 
    0.555, 
 
    0.293 
 
]; 
 

 
let output = zip(metrodates, figures).map(([date, data]) => ({date, data})); 
 

 
console.log(output);


另一種選擇是使一個通用地圖功能,它接受一個以上的源陣列。映射函數將從每個源列表中接收一個值。有關其使用的更多示例,請參閱Racket's map procedure

這個答案可能看起來最複雜,但它也是最通用的,因爲它接受任意數量的源數組輸入。

const isEmpty = xs => xs.length === 0; 
 
const head = ([x,...xs]) => x; 
 
const tail = ([x,...xs]) => xs; 
 

 
const map = (f, ...xxs) => { 
 
    let loop = (acc, xxs) => { 
 
    if (xxs.some(isEmpty)) 
 
     return acc; 
 
    else 
 
     return loop([...acc, f(...xxs.map(head))], xxs.map(tail)); 
 
    }; 
 
    return loop([], xxs); 
 
} 
 

 
let metrodates = [ 
 
    "2008-01", 
 
    "2008-02", 
 
    "2008-03" 
 
]; 
 

 
let figures = [ 
 
    0, 
 
    0.555, 
 
    0.293 
 
]; 
 

 
let output = map(
 
    (date, data) => ({date, data}), 
 
    metrodates, 
 
    figures 
 
); 
 

 
console.log(output);