EN
JavaScript - ordered object properties
20 points
In this article, we would like to show how to achieve object that stores ordered properties in JavaScript.
In JavaScript, object properties are not ordered by default, but it is possible to work with ordered properties only when we use:
- some logic that sorts properties, that requires re-sort operation on each change,
- embedded
Map
class, - custom implementation of
Map
class.
Note: this approach has been introduced in ES2015.
xxxxxxxxxx
1
var map = new Map();
2
3
map.set('key 5', 'a');
4
map.set('key 4', 'b');
5
map.set('key 3', 'c');
6
map.set('key 2', 'd');
7
map.set('key 1', 'e');
8
9
map.delete('key 3');
10
11
console.log('map size: ' + map.size);
12
console.log('key 2 -> ' + map.get('key 2'));
13
console.log('key 3 -> ' + map.get('key 3'));
14
console.log('key 4 -> ' + map.get('key 4'));
15
console.log('key 6 -> ' + map.get('key 6'));
16
17
map.forEach(function(value, key) {
18
console.log('key: ' + key + ', value: ' + value);
19
});
Output (with NodeJS):
xxxxxxxxxx
1
map size: 4
2
3
key 2 -> d
4
key 3 -> undefined
5
key 4 -> b
6
key 6 -> undefined
7
8
key: key 5, value: a
9
key: key 4, value: b
10
key: key 2, value: d
11
key: key 1, value: e
In this article you can find custom implementation of Map
class that stores items in ordered way.