i have myData map as below
var myData = new Object();
myData[10427] = "Description 10427";
myData[10504] = "Description 10504";
myData[10419] = "Description 10419";
but now when i iterate over myData, i don't get same sequnce in chrome and IE works fine in firefox. It iterates in ascending order of key
for (var key in myData) {
alert("key is"+key);
}
i get the output in ascending order in alert as 10419,10427,10504
How i can make sure to iterate in same order as data as inserted in map?
A Map is a collection of key/value pairs that can use any data type as a key and can maintain the order of its entries.
Here, the original insertion order of HashMap is [01, 03, 04, 02], but the output is different [01, 02, 03, 04]. It did not maintain the original insertion order of the elements.
The underlying issue isn't because of map , which should preserve the order. Rather, user.jobs itself may be in a different order (in each test) since there isn't any explicit order by clause used. Without an explicit order by , you can't guarantee the order of the jobs even if you create them in a specific order.
Iterate through a Map using JavaScript # Use the forEach() method to iterate over a Map object. The forEach method takes a function that gets invoked for each key/value pair in the Map , in insertion order. The function gets passed the value, key and the Map object on each iteration.
ES6 Maps preserves the insertion order.
The set method is used for setting the key value pairs
var myData = new Map();
myData.set(10427, "Description 10427");
myData.set(10504, "Description 10504");
myData.set(10419, "Description 10419");
Map keys and values are printed using
myData.forEach((value,key) => console.log(key, value));
This will print the keys and values in the insertion order
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With