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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With