简体   繁体   English

给定一组数组,如何将其转换为对象?

[英]Given an array of arrays how do I convert this to an object?

Given an array of arrays, how do I convert this to a JavaScript object with the condition that the first element of each array of the internal arrays will be a key of a new JavaScript object, the subsequent element would be the value?给定一个数组数组,如何将其转换为 JavaScript 对象,条件是内部数组的每个数组的第一个元素将是新 JavaScript 对象的键,后续元素将是值?

And if there is more than one occurrence of the element in the first position of the internal arrays only create a single key corresponding to this element.如果在内部数组的第一个位置出现多个元素,则只创建与该元素对应的单个键。

For example:例如:

var arr = [['a', 'b'], ['c', 'd'], ['a', 'e']]

should return:应该返回:

var obj = {a: ["b", "e"], c: ["d"]}

Here there are 2 occurrences of a within arr therefore only a single key a was created in obj along with c这里在arr出现了 2 次a ,因此在obj只创建了一个键ac

Using Array.prototype.reduce function, you can accomplish this as follows.使用Array.prototype.reduce函数,您可以按如下方式完成此操作。

 var arr = [['a', 'b'], ['c', 'd'], ['a', 'e']]; const output = arr.reduce((acc, cur) => { acc[cur[0]] ? acc[cur[0]].push(cur[1]) : acc[cur[0]] = [ cur[1] ]; return acc; }, {}); console.log(output);

This is an alternative:这是一个替代方案:

var arr = [['a', 'b'], ['c', 'd'], ['a', 'e']]
const obj = {}
arr.forEach(([k, v]) => obj[k] = [...obj[k] ?? [], v])

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

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