假设我有三个数组,描述了一些名称,阅读的书籍数量以及这些人[名字]中有多棒:
let names = ["Mary","Joe","Kenan"]; let numberOfBooks = [2,1,4]; let awesomenessLevel = ["pretty cool","meh","super-reader"];
我正在尝试使用.reduce()将它们组合在一起以创建一个包含每个数组中相关索引的对象数组,但我失败了:
let people = [ { name: "Mary",noOfBooks: 2,awesomeness: "pretty cool" },{ name: "Joe",noOfBooks: 1,awesomeness: "meh" },{ name: "Kenan",noOfBooks: 4,awesomeness: "super-reader" } ]
我也减少了它:
let arrFinal = []; names.reduce(function(all,item,index) { arrFinal.push({ name: item,noOfBooks: numberOfBooks[index],awesomeness: awesomenessLevel[index] }) },[]);
解决方法
你可以用map来做,像这样:
let result = names.map( (v,i) => ({ name: names[i],noOfBooks: numberOfBooks[i],awesomenessLevel: awesomenessLevel[i] }));
let names = ["Mary","super-reader"]; let result = names.map( (v,awesomenessLevel: awesomenessLevel[i] })); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
在这种情况下,map比reduce更好,因为names数组中的元素数量(或其他两个元素中的任何一个)与输出中所需的元素数量相同.在这种情况下,使用地图更自然.