Array to object reduce

半腔热情 提交于 2019-12-11 14:35:58

问题


Hello I want to transform array to object

input = [1,2,3]

expected output = {1:1,2:2,3:3}

I tried this

const arrToObj = (arr) => {
  arr.reduce((acc, curr, i, arr)=> {
    acc[curr]=arr[i]
  },{})
}
console.log(arrToObj([1,2,3,4,5,6,7,8,9]))

but it throws errror in second iteration. What is wrong and how to make it work?


回答1:


What you have tried so far has two problems

The first is serious:

You forgot to return from your accumulating function, so it returns undefined.

It throws the second time around because Array.prototype.reduce passes the specified seed as the first argument on the first call to the accumulating function but, on the second call, it passes the result of the first call.

So initially, reduce calls your function like this

result = accumulatorFunction(seed, arr[0], 0, arr);

which expands to

result = accumulatorFunction({}, 1, 0, [1, 2, 3]);

The subsequent call, however, is looks like this

result = accumulatorFunction(result, arr[1], 1 arr);

which expands to

result = accumulatorFunction(undefined, 2, 1, [1, 2, 3]);

So you need to write something like

arr.reduce((acc, curr, i, arr) => {
  acc[curr] = arr[i];
  return acc;
}, {});

Another issue with your code, and more one of style, is that you needlessly provide and use the fourth argument passed to the accumulating function. This argument is just the array itself anyway. Using it is awkward and makes your code more complex, more prone to mistakes, and harder to understand.

Instead write

arr.reduce((acc, curr) => {
  acc[curr] = curr;
  return acc;
}, {});

"use strict";

const input = [1, 2, 3];

const output = input.reduce((acc, curr) => {
  acc[curr] = curr;
  return acc;
}, {});

console.log(output);



回答2:


something like this?

const arr = [1,2,3,4,5,6,7,8,9]
const obj = arr.reduce((accumulator, currentValue, index) => {
  accumulator[index+1] = currentValue;
  return accumulator;
}, {});

console.log(obj)



回答3:


const arrToObj = a => a.reduce((r, v) => (r[v] = v, r), {})

console.log( arrToObj( [1, 2, 3] ) )

If the values match the indexes, it can be even simpler with ECMAScript 2018 Spread syntax :

console.log( { ...[, 1, 2, 3] } )


来源:https://stackoverflow.com/questions/49469699/array-to-object-reduce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!