2016-04-15 155 views
-1

我試圖根據原始數組元素的索引創建一個新數組。原始數組中的元素是對象,因此我們的目標是從兩個連續元素中提取信息並將它們組合到新元素中:來自no.1和no.2的信息構成第一個元素,no.3和no.4形式第二個等等。原始數組的長度是偶數。我如何用map函數來做到這一點?基於索引的JavaScript映射數組

樣本:原數組:

[{name: Name1,age: Age1,year: Year1,desc: Desc1}, 
{name: Name2,age: Age2,year: Year2,desc: Desc2}, 
{name: Name3,age: Age3,year: Year3,desc: Desc3}, 
{name: Name4,age: Age4,year: Year4,desc: Desc4}] 

而且我希望有一個新的數組是這樣的:

[{firstName: Name1, 
    secondName: Name2, 
    firstAge: Age1, 
    secondAge: Age2, 
    firstYear: Year1, 
    seconnTear: Year2, 
    firstDesc: Desc1, 
    secondDesc: Desc2}, 

{firstName: Name3, 
    secondName: Name4, 
    firstAge: Age3, 
    secondAge: Age4, 
    firstYear: Year3, 
    seconnTear: Year4, 
    firstDesc: Desc3, 
    secondDesc: Desc4}, 
    }] 

正常循環當然會做到這一點;我只想了解JavaScript映射函數的使用。

+1

先給您輸入的實例和預期產出 – Chris

+1

你的問題不是很清楚,特別是因爲根據您的描述,'.MAP()'就似乎沒有有用。只寫一個簡單的循環,增加2就有什麼問題? – 2016-04-15 01:45:01

+1

那麼,你不會用'map()'輸入'map()'來匹配輸出的長度。 – jdphenix

回答

1

這是一個非常典型的Array.prototype.reduce()工作。以下應該能夠做你以後的事情。它首先將inArr中的後續兩個對象耦合在一起,方法是先填充第一個數據並將其推入reduced,然後在下一輪reduce操作中填充第二個數據。

var inArr = [{name: "Name1",age: "Age1",year: "Year1",desc: "Desc1"}, 
 
      {name: "Name2",age: "Age2",year: "Year2",desc: "Desc2"}, 
 
      {name: "Name3",age: "Age3",year: "Year3",desc: "Desc3"}, 
 
      {name: "Name4",age: "Age4",year: "Year4",desc: "Desc4"}], 
 
reduced = inArr.reduce((p,c,i) => { var j = p.length-1; 
 
     \t        if (!(i%2)) { 
 
     \t        p.push({ firstName: c.name, 
 
               secondName: "", 
 
               firstAge: c.age, 
 
               secondAge: "", 
 
               firstYear: c.year, 
 
               secondYear: "", 
 
               firstDesc: c.desc, 
 
               secondDesc: ""}); 
 
     \t        } else { 
 
     \t        p[j].secondName = c.name; 
 
     \t        p[j].secondAge = c.age; 
 
     \t        p[j].secondYear = c.year; 
 
     \t        p[j].secondDesc = c.desc; 
 
     \t        } 
 
            return p; }, []); 
 
document.write('<pre> ' + JSON.stringify(reduced, 0, 2) + '</pre>');