最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

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

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?

Share Improve this question edited Oct 4, 2018 at 21:15 Ori Drori 192k32 gold badges237 silver badges227 bronze badges asked Oct 4, 2018 at 21:06 N1B4N1B4 3,4531 gold badge23 silver badges25 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 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'));

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

发布评论

评论列表(0)

  1. 暂无评论