我想将两个数组合并到一个对象数组中......
第一个数组是日期(字符串):
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 :(得分:5)
最简单的方法可能是使用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);

另一种选择是创建一个通用的 zip 函数,它将两个输入数组整理成一个数组。这通常被称为" zip"因为它像拉链上的牙齿一样交织输入。
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);

另一种选择是制作一个通用的 map 函数,该函数接受多个源数组。映射函数将从每个源列表中接收一个值。有关其使用的更多示例,请参阅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);

答案 1 :(得分:2)
如果您使用lodash,则可以使用 zipWith + ES6 shorthand propery names + ES6 Arrow functions 进行单行,否则请参阅@noami&# 39;答案。
const metrodata = _.zipWith(figures, metrodates, (data, date)=> ({ data, date }));