简体   繁体   中英

How to convert an array of key–value arrays to an array of objects with .reduce function?

Hello i am not a javascript programmer. What I want to achieve is that the output down with reduce. This script is going to be used in google scripts for that reason you have to use the reduce function.

Input

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

Output

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

Like that:

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

I know you specifically asked for .reduce. But reduce is for reducing a set to a single value. The function you asked for is a service for .map. And Google Scripts will understand it also. Take a look at this example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM