如何将数组转换为对象? [英] How to transform Array to Object?

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

问题描述

变换这样的数组的最佳方法是什么:

What is the best way to transform an array like this:

const arr = [
  { name: 'Bob' },
  { name: 'Ben' }
  { name: 'Cole' }
  { name: 'Mary' }
  { name: 'Travis' }
]

到这样的对象:

const obj = {
  'B': ['Bob', 'Ben'],
  'C': ['Cole'],
  'M': ['Mary'],
  'T': ['Travis']
}

仅使用香草JS

推荐答案

我使用reduce函数创建了一个数组,其中键是名称的第一个字母,并从对象中重构名称".如果键存在于数组中,则名称会被推送(使用扩展运算符).否则,它仅使用一个元素创建密钥.

I created an array where the key is the first letter of the name using the reduce function and restructuring the 'name' from the objects. If the key exists in the array the name is pushed (using spread operator). Else, it creates the key with only one element.

const arr = [
  { name: 'Bob' },
  { name: 'Ben' },
  { name: 'Cole' },
  { name: 'Mary' },
  { name: 'Travis' }
];

const obj = arr.reduce((res, {name})=>{
  res[name[0]] = res[name[0]] ? [...res[name[0]],name] : [name];
  return res;
}, {});

console.log(obj);

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

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