How to preserve order of hashmap in JavaScript?

馋奶兔 提交于 2020-08-24 03:22:49

问题


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.


回答1:


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.




回答2:


You can use a second array to preserve the order of keys.

var order = [];

//add something to map
map['a'] = 1;
order.push('a');

map['b'] = 2;
order.push('b');

//iterate in order
for (var i=0; i< order.length;++i) {
  alert(map[order[i]);
} 

Preserving consistency of the order array might be tricky since you always need to update the order array when you modify the original map.



来源:https://stackoverflow.com/questions/25041814/how-to-preserve-order-of-hashmap-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!