需求
有这么两个数组
let metrodates = ["2008-01","2008-02","2008-03",..ect];let figures = [0,0.555,0.293,..ect]
想要这样的结果
let result = [{data: 0, date: "2008-01"},{data: 0.555, date: "2008-02"},{data: 0.293, date: "2008-03"},..ect];
方案一
let result = [];for(let index in metrodates){result.push({data: figures[index], date: metrodates[index]});}
方案二
let result = metrodates.map((date,i) => ({date, data: figures[i]}));
此方案使用了ES6中的map,简洁,但本质还是遍历,显得有些low
方案三
const zip = ([x,...xs], [y,...ys]) => {if (x === undefined || y === undefined)return [];elsereturn [[x,y], ...zip(xs, ys)];}let result = zip(metrodates, figures).map(([date, data]) => ({date, data}));
方案四
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;elsereturn loop([...acc, f(...xxs.map(head))], xxs.map(tail));};return loop([], xxs);}let result = map((date, data) => ({date, data}), metrodates, figures);
此方案是方案三的加强版,它能接受多个数组映射成对象数组,威力无比!
原文链接:https://www.cnblogs.com/guanghe/p/11445426.html
