4

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?

4 Answers 4

13

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Why does the key need to be bracketed ([k]) in the map return? I was doing something similar but had ...=> ({k: v}) without the brackets.
when you create an object like this { k: v }, the key name is the letter k, and not the value of k. To get the value, you need to use computed property names - [k].
6

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

Comments

2

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.