Home > Blockchain >  How to store map values into an array to its first position using typescript?
How to store map values into an array to its first position using typescript?

Time:09-23

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

(see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries#converting_a_map_to_an_object)

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: Maps 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.

  • Related