I have a map and want to store map values into an array but to its first position only. My map is:
this.mapValues.set("1","First");
this.mapValues.set("2","Second");
this.mapValues.set("3","Third");
Then afterwards I want it to convert it in form:
[{1:First, 2: Second, 3: Third}]
CodePudding user response:
I think something like
const myarray = [Object.fromEntries(this.mapValues)]
might do what you want
I'm not sure that all maps can be converted to objects, since maps can have any kind of value as keys, but in the case of your example it should work.
CodePudding user response:
Not exactly sure of the required functionality here. Why exactly use a Map
only to convert it to an object enclosed in an array later.
Nevertheless, you could use Array#reduce
with Array#from
and spread syntax to convert the map to an object. Then later enclose it in an array.
let mapValues = new Map();
mapValues.set("1","First");
mapValues.set("2","Second");
mapValues.set("3","Third");
const arr = [Array.from(mapValues).reduce((acc, curr) => ({
...acc,
[curr[0]]: curr[1]
}), Object.create(null))];
console.log(arr);
Note: Map
s can have non-string keys, object literals can't. In your case however it shouldn't be an issue.
Edit: Alternative to other solution when Object#fromEntries
isn't available.