【问题标题】:ES6: Merge two arrays into an array of objectsES6:将两个数组合并成一个对象数组
【发布时间】:2017-02-04 07:26:41
【问题描述】:

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

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

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

【问题讨论】:

标签: arrays ecmascript-6


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    如果您使用lodash,则可以使用zipWith + ES6 shorthand propery names + ES6 Arrow functions 进行单行,否则请参阅@noami 的答案。

    const metrodata = _.zipWith(figures, metrodates, (data, date)=> ({ data, date }));
    

    【讨论】:

      猜你喜欢
      • 2018-11-23
      • 2022-01-04
      • 1970-01-01
      • 2018-09-21
      • 1970-01-01
      • 2016-11-12
      • 2018-05-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多