Languages
[Edit]
EN

JavaScript - ordered object properties

20 points
Created by:
Dollie-Rutledge
806

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.

 

Embedded Map class usage example

Note: this approach has been introduced in ES2015.

// ONLINE-RUNNER:browser;

var map = new Map();

map.set('key 5', 'a');
map.set('key 4', 'b');
map.set('key 3', 'c');
map.set('key 2', 'd');
map.set('key 1', 'e');

map.delete('key 3');

console.log('map size: ' + map.size);
console.log('key 2 -> ' + map.get('key 2'));
console.log('key 3 -> ' + map.get('key 3'));
console.log('key 4 -> ' + map.get('key 4'));
console.log('key 6 -> ' + map.get('key 6'));

map.forEach(function(value, key) {
    console.log('key: ' + key + ', value: ' + value);
});

Output (with NodeJS):

map size: 4

key 2 -> d
key 3 -> undefined
key 4 -> b
key 6 -> undefined

key: key 5, value: a
key: key 4, value: b
key: key 2, value: d
key: key 1, value: e

 

Custom implementation of Map class

In this article you can find custom implementation of Map class that stores items in ordered way.

 

References

  1. Map class - MDN docs

Alternative titles

  1. JavaScript - ordered map
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join