简体   繁体   中英

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?

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'));

Yes, you can use reduce - on each iteration, extract both items from the array (as the key and the value), assign the value to the appropriate key in the accumulator, and return the accumulator:

 const input = [[35, "Bill"], [20, "Nancy"], [27, "Joan"]]; const obj = input.reduce((a, [val, key]) => { a[key] = val; return a; }, {}); console.log(obj);

You could map the items for new objects and assign all to a single object with Object.assign .

 var array = [[35, "Bill"], [20, "Nancy"], [27, "Joan"]], object = Object.assign(...array.map(([v, k]) => ({ [k]: v }))); console.log(object);

You can use reduce with Object.assign :

 let array = [[35, "Bill"], [20, "Nancy"], [27, "Joan"]]; let result = array.reduce((acc, [value, key]) => Object.assign(acc, { [key]: value }), {}); console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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