Reputation: 675
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?
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
Upvotes: 0
Views: 47
Reputation: 76
This is an alternative:
var arr = [['a', 'b'], ['c', 'd'], ['a', 'e']]
const obj = {}
arr.forEach(([k, v]) => obj[k] = [...obj[k] ?? [], v])
Upvotes: 2
Reputation: 10193
Using Array.prototype.reduce
function, you can accomplish this as follows.
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);
Upvotes: 2