New*_*oJS 2 arrays ecmascript-6
我有两个数组,我想合并到一个对象数组...
第一个数组是日期(字符串):
let metrodates = [
"2008-01",
"2008-02",
"2008-03",..ect
];
Run Code Online (Sandbox Code Playgroud)
第二个数组是数字:
let figures = [
0,
0.555,
0.293,..ect
]
Run Code Online (Sandbox Code Playgroud)
我想合并它们来制作一个像这样的对象(所以数组项与它们相似的索引相匹配):
let metrodata = [
{data: 0, date: "2008-01"},
{data: 0.555, date: "2008-02"},
{data: 0.293, date: "2008-03"},..ect
];
Run Code Online (Sandbox Code Playgroud)
到目前为止我这样做是这样的:我创建一个空数组然后循环通过前两个数组中的一个来获取索引号(前两个数组的长度相同)...但是有更简单的方法(在ES6中) )?
let metrodata = [];
for(let index in metrodates){
metrodata.push({data: figures[index], date: metrodates[index]});
}
Run Code Online (Sandbox Code Playgroud)
最简单的方法可能是使用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);
Run Code Online (Sandbox Code Playgroud)
另一种选择是创建一个通用的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);
Run Code Online (Sandbox Code Playgroud)
另一个选择是创建一个接受多个源数组的通用映射函数.映射函数将从每个源列表中接收一个值.有关其使用的更多示例,请参阅Racket的映射过程.
这个答案可能看起来最复杂,但它也是最通用的,因为它接受任意数量的源数组输入.
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);
Run Code Online (Sandbox Code Playgroud)