基于索引的JavaScript地图数组

时间:2016-04-15 01:42:00

标签: javascript arrays

我正在尝试根据原始数组元素的索引创建一个新数组。原始数组中的元素是对象,因此目标是从两个连续元素中提取信息并将它们组合到新元素:来自no.1和no.2的信息形成第一个元素,no.3和no.4形式第二个,等等。原始数组的长度是偶数。如何使用map函数执行此操作?

示例:原始数组:

[{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 map函数的使用。

1 个答案:

答案 0 :(得分: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;
      	                            if (!(i%2)) {
      	                              p.push({ firstName: c.name,
                                              secondName: "",
                                                firstAge: c.age,
                                               secondAge: "",
                                               firstYear: c.year,
                                              secondYear: "",
                                               firstDesc: c.desc,
                                              secondDesc: ""});
      	                            } else {
      	                              p[j].secondName = c.name;
      	                              p[j].secondAge  = c.age;
      	                              p[j].secondYear = c.year;
      	                              p[j].secondDesc = c.desc;
      	                            }
                                    return p; }, []);
document.write('<pre> ' + JSON.stringify(reduced, 0, 2) + '</pre>');