简体   繁体   English

如何将数组转换为对象?

[英]How to transform Array to Object?

What is the best way to transform an array like this:像这样转换数组的最佳方法是什么:

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

to an object like:到一个对象,如:

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

Using only vanilla JS仅使用香草 JS

You can use array#reduce .您可以使用array#reduce Iterate through each object of your array and then extract out the first letter and add names corresponding to it.遍历数组的每个对象,然后提取第一个字母并添加与其对应的名称。

 const arr = [{name: 'Bob'}, {name: 'Ben'}, {name: 'Cole'}, {name: 'Mary'}, {name: 'Travis'}], result = arr.reduce((r,{name}) => { r[name[0]] = r[name[0]] || []; r[name[0]].push(name); return r; },{}); console.log(result);

Vanilla JS you say?你说香草JS? Here you go干得好

 let nil = x => x === undefined; let empty = ([h]) => nil(h); let first = ([h]) => h; let last = ([h, ...t]) => empty(t) ? h : last(t); let map = ([h, ...t], f) => nil(h) ? [] : [f(h), ...map(t, f)]; let reduce = ([h, ...t], f, i) => nil(h) ? i : reduce(t, f, f(i, h)); let tab = (a, f) => map(a, x => [x, f(x)]); let push = (a, x) => nil(a) ? [x] : [...a, x]; let groupBy = (a, f) => _groupBy(tab(a, f)); let _groupBy = ka => reduce(ka, (g, [x, k]) => ({...g, [k]: push(g[k], x)}), {}); /// const arr = [{ name: 'Bob' },{ name: 'Ben' },{ name: 'Cole' },{ name: 'Mary' },{ name: 'Travis' }] z = groupBy(map(arr, x => x.name), first) console.log(z)

No built-ins!没有内置!

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.我使用reduce 函数创建了一个数组,其中键是名称的第一个字母,并从对象中重构“名称”。 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);
let obj = {};
arr.forEach( e => {
  const name = e.name;
  if (!obj[name.charAt(0)]) obj[name.charAt(0)] = [];
  obj[name.charAt(0)].push(name);
})

I'm generating a new object and adding to it news keys based in the first char of the name values (only if the key hasn't been already added).我正在生成一个新对象并根据名称值的第一个字符向其中添加新闻键(仅当尚未添加键时)。 Then, I add each value to the key that corresponds.然后,我将每个值添加到对应的键中。

I think this thread is missing a non functional answer, so here it is:我认为这个线程缺少一个非功能性的答案,所以这里是:

const obj = {};

for(const {name} of arr)
  (obj[name[0]] || (obj[name[0]] = [])).push({name});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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