arrays - ES6 : Merge two arrays into an array of objects

标签 arrays ecmascript-6

我有两个数组,我想将它们合并到一个对象数组中...

第一个数组是日期(字符串):

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]});
  }

最佳答案

最简单的方法可能是使用 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 函数,它将两个输入数组整理成一个数组。这通常称为“ zipper ”,因为它像 zipper 上的齿一样交错输入。

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);

<小时/>

另一种选择是创建一个通用的ma​​p函数,它接受多个源数组。映射函数将从每个源列表接收一个值。请参阅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);

关于arrays - ES6 : Merge two arrays into an array of objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39711528/

相关文章:

python - numpy 中的三重张量积

javascript - 如何正确计算数组中的出现次数?

javascript - 带有 babel-loader 的 Webpack 无法识别 import 关键字

javascript - 使用 react.js 从嵌套子项中获取表单值

javascript - 将变量作为属性名称传递

javascript - @Component 和 Class 之间的 angular2 关系

Javascript - 在前端逐行显示数组

arrays - Sequelize - 在数组列中查找项目

javascript - 在正则表达式中反转捕获组

php - Laravel 删除数组中的第一个 -