Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve order of hashmap in JavaScript?

Java has LinkedHashMap but there doesn't seem to be a similar solution in JavaScript.

Basically, I want to be able to say

var map = {};
map['a'] = 1;
map['b'] = 2;

Then when I iterate over the map, they are always in [{a:1}, {b:2}...] order.

like image 508
pfrank Avatar asked Sep 05 '25 19:09

pfrank


1 Answers

I believe JavaScript Map object can help you to solve this issue:

let myObject = new Map();
myObject.set('z', 33);
myObject.set('1', 100);
myObject.set('b', 3);

for (let [key, value] of myObject) {
  console.log(key, value);
}
// z 33
// 1 100
// b 3

Also, please take into consideration that this is ES6 (ES2015) standard. Cheers.

like image 190
theVoogie Avatar answered Sep 08 '25 12:09

theVoogie