【问题标题】:How to convert an array of key–value arrays to an array of objects with .reduce function?如何使用 .reduce 函数将键值数组转换为对象数组?
【发布时间】:2018-07-13 15:23:58
【问题描述】:

您好,我不是 javascript 程序员。我想要实现的是输出随着减少而下降。此脚本将用于 google 脚本,因此您必须使用 reduce 函数。

输入

[
  [ 'foo', 3.672698 ],
  [ 'bar', 71.999747 ],
  [ 'baz', 107.400002 ],
]

输出

[
  { 
    name: 'foo', 
    money: 3.672698 
  },
  { 
    name: 'bar', 
    money: 71.999747 
  },
  { 
    name: 'baz', 
    money: 107.400002 
  },
]

【问题讨论】:

  • 您的输入是我所看到的数组数组,但是 foo、bar 和 baz 是什么?只是变量?字符串类型的?
  • 与您通常使用Array#reduce 的方式相同。 [] 的初始值,并确保在回调中返回累加器。

标签: javascript google-apps-script reduce


【解决方案1】:

这样:

const input = [
  [ 'foo', 3.672698 ],
  [ 'bar', 71.999747 ],
  [ 'baz', 107.400002 ],
];

const output = input.reduce((acc, item) => {
  acc.push({
    name: item[0],
    money: item[1]
  });
  return acc;
}, [])

console.log(output);

【讨论】:

    【解决方案2】:

    我知道您专门要求使用 .reduce。但 reduce 用于将集合减少为单个值。您要求的功能是 .map 的服务。 Google Scripts 也会理解它。看看这个例子:

    var arr = [
      [ 'foo', 3.672698 ],
      [ 'bar', 71.999747 ],
      [ 'baz', 107.400002 ],
    ]
    
    var res = arr.map(function(item){ 
         return {name: item[0], money: item[1]};
    });
    console.log(res);

    【讨论】:

      猜你喜欢
      • 2020-08-24
      • 2017-12-24
      • 2018-12-26
      • 1970-01-01
      • 2021-12-27
      • 2019-01-14
      • 1970-01-01
      • 2021-02-14
      • 1970-01-01
      相关资源
      最近更新 更多