减少对象数组 [英] Array to object reduce

查看:58
本文介绍了减少对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我想将数组转换为对象

Hello I want to transform array to object

input = [1,2,3]

input = [1,2,3]

预期输出= {1:1,2:2,3:3}

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

我尝试过

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?

推荐答案

到目前为止,您尝试过的问题有两个问题

What you have tried so far has two problems

第一个很严重:

您忘了从累加函数中返回,因此返回未定义

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

它第二次抛出,因为 Array.prototype.reduce 在第一次调用时将指定的种子作为第一个参数传递给累加函数,但是在第二次调用时,它将指定的种子传递给第一次调用的结果。

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

扩展为

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

但是随后的呼叫看起来像这样

The subsequent call, however, is looks like this

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

扩展为

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

所以您需要编写类似

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.

相反,编写

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

这篇关于减少对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆