Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 2D array to object using map or reduce in javascript

Is it possible to convert

[[35, "Bill"], [20, "Nancy"], [27, "Joan"]]

to

{"Bill": 35, "Nancy": 20, "Joan": 27}

using the .map() or .reduce() methods?

I can convert the array using:

const arr = [[35, "Bill"], [20, "Nancy"], [27, "Joan"]];

let obj = {};

for (let item of arr) {
  obj[item[1]] = item[0];
}

console.log(obj);

But my attempts to do this using map or reduce are failing. Any ideas?

like image 860
N1B4 Avatar asked Dec 05 '22 11:12

N1B4


1 Answers

If supported, you can use Object.fromEntries() to convert an array of [key, value] pairs to an object. In this case, the pairs are [value, key], so we'll need to map them first to an array of [key, value] pairs.

const arr = [[35, "Bill"], [20, "Nancy"], [27, "Joan"]];

const obj = Object.fromEntries(arr.map(([v, k]) => [k, v]));

console.log(obj);

Use Array.map() to create an array of objects where each contains a single key/value. Combine them to a single object by spreading into Object.assign():

const arr = [[35, "Bill"], [20, "Nancy"], [27, "Joan"]];

const obj = Object.assign(...arr.map(([v, k]) => ({ [k]: v })));

console.log(obj);

If you need to use the object as a dictionary, a better solution would be to convert the array of tuples to a Map:

const arr = [[35, "Bill"], [20, "Nancy"], [27, "Joan"]];

const map = new Map(arr.map(([v, k]) => [k, v]));

console.log(map.get('Bill'));
like image 98
Ori Drori Avatar answered Feb 08 '23 23:02

Ori Drori