Reputation: 8791
I am new to programming in general and am looking to convert a Javascript map into array of objects. For example, convert the input constant into the output constant:
const input = new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
]);
const output = [
{ number: 1, letter: 'one' },
{ number: 2, letter: 'two' },
{ number: 3, letter: 'three' }
];
This might be a simple code but I cannot find any reference. Any advice? Thanks!
Upvotes: 2
Views: 5414
Reputation: 8107
Contrary to other answers, this one does not create an unnecessary intermediate array:
const input = new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
]);
const output = Array.from(input, ([number, letter]) => ({number, letter}));
console.log(output);
From MDN:
Array.from()
has an optional parametermapFn
, which allows you to execute a function on each element of the array being created, similar tomap()
. More clearly,Array.from(obj, mapFn, thisArg)
has the same result asArray.from(obj).map(mapFn, thisArg)
, except that it does not create an intermediate array, andmapFn
only receives two arguments (element
,index
) without the whole array, because the array is still under construction.
Upvotes: 0
Reputation: 11011
Use ...
operator and map
method.
const input = new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
]);
const output = [...input].map(([number, letter]) => ({number, letter}))
console.log(output);
Upvotes: 1
Reputation: 38
You can do it by iterating over the Map using For-of iteration and pushing the object into a new array. Refer to for-of operation for Map
var arr = [];
for(var [key, val] of input) {
arr.push({ integer: key, letter: val})
}
Upvotes: 0
Reputation: 5064
You don't have to convert to anything. There is a forEach method for Map. You can do the following using Map.protoType.forEach,
const input = new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
]);
let output = [];
input.forEach((letter, number) => {
output.push({number, letter});
})
console.log(output);
Upvotes: 1
Reputation: 47127
Something like this might work:
const output = Array.from(input).map(([number, letter]) => ({number, letter}));
The basic idea is that you convert the map input
to an array, and then map each entry.
Upvotes: 6