Should You Stop Using Objects and Arrays to Store Data?

Should You Stop Using Objects and Arrays to Store Data?

ES6 has other ways of handling data structures and values in the form of Set and Map

Photo by [Alvaro Reyes](https://cdn.hashnode.com/res/hashnode/image/upload/v1630754125676/tBKgUe7S0.html) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)Photo by Alvaro Reyes on Unsplash

For years, programmers have used objects and arrays to store data. This trend is not only limited to JavaScript.

There was simply no other choice besides these two to store multiple values and handle data structures.

There were several limitations however while using objects and array such as:

  1. An array can store duplicate elements.

  2. No method to find the length of the object as we have for arrays.

  3. Only Strings can be stored in objects and it doesn’t remember the insertion order.

  4. Developers had to choose either arrays or objects depending upon their use case.

  5. Third-party libraries like Lodash were used to enhance the capabilities of the array

But with the launch of ES6 in 2015, things changed for the better.

ES6 brings in support for Map and Set which aims to overcome the limitations stated above.

What are Set and Map?

As stated before, both of these are introduced in the ES6 version of JavaScript.

Set is an ordered collection of unique elements. ‘Unique elements’ is the primary takeaway because it means that no duplicate elements can be stored in a set. It doesn’t have a key-value pair system though.

A Map on the other hand is a combination of array and object data structure. It is a collection of key-value pairs like objects but it also remembers the insertion format and has a length(.size) property.

I will be going over Set first and then Map.

Declaration and Initialisation of Set

A Set can be initialized like this:

const set = new Set();

Adding and Removing Elements from Set

You can easily insert elements into the set using the .add() method.

const set = new Set();

set.add('John');

set.add('Martha')

set.add('Bryan');

set.add('John');

// set = {'John','Martha','Bryan'}

This is where things get a little interesting. A Set in JavaScript borrows a lot of properties from a mathematical set and only contains unique elements.

Removing elements is also very straightforward using the .delete() method to delete a single element and .clear() method to remove all the elements

set.add('John');

set.add('Martha')

set.add('Bryan');

set.delete('Martha')

//set = {'John','Bryan'}

set.clear(); // removes all the element

Size of Set

Using the .sizemethod, one can easily find the size of the set which can be helpful.

set.add('a')

set.add('b');

set.add('c');

console.log(set.size) // => 3

Accessing Elements in a Set

Set behaves differently when trying to log or access its values. You can log the array and see the elements but the same is not true for a set.

var arr=[1,2,3];

const set = new Set(arr);

console.log(set) // => [object Set]

console.log(arr) // => (3) [1,2,3]

To access Set, we need a SetIterator() to get all the values.

JavaScript provides a property .values() to get an iterator which we can then use in combination with a loop to retrieve all the values.

This is demonstrated by the code snippet below:

var arr=[1,2,3];

const set = new Set(arr);

var iterator=set.values()

console.log(iterator.next().value) //1

The easier way to retrieve all the elements is by using .forEach() and is given below:

var arr=[1,2,3];

const set = new Set(arr);

set.forEach(v=>console.log(v))

Output:

1
2
3

Additionally, you can check if a value exists or not using .has()method which returns true if the element is found.

var arr=[1,2,3];

const set = new Set(arr);

console.log(set.has(1)); // true

It is worth mentioning that methods like keys()and entries() are available for Set despite the fact that Set doesn’t support key-value pair elements.

Set vs Array

Set and Array tend to perform and handle the same operations however there exists some difference.

The biggest difference is that Set can’t have duplicate items like Array and Set provides an easier method to delete items.

Additionally, the elements of the set are iterable in the insertion order.

Like the mathematical set, the Set in JavaScript can also be used to perform operations like union and intersection which can be used while merging data or finding common elements in two sets.

You can full list of methods and guide on Set here.

Initialising and Declaring Map

Similar to Set, Map can also be declared in the same fashion.

const map = new Map();

Adding and Removing Elements from Map

The Map supports the object-like key-value pairs. Therefore, when adding value, we need to provide a key as well.

This is different from what we saw with the Set.

const map = new Map();

map.set('Name', 'iPhone'); // map.set(key,value) format

map.set('Brand', 'Apple');

map.set('Price', '$1000');

To remove a value from the Map, we can simply pass the key into the .delete()property.

const map = new Map();

map.set('Name', 'iPhone'); 

map.set('Brand', 'Apple');

map.set('Price', '$1000');

map.delete('Price'); //removes the element with key 'Price'

Like Set, we can use .clear() to remove all the elements.

map.clear() // removes all the element

Size of Map

The size(length) of the map can easily be retrieved using the .size property.

const map = new Map();

map.set('Name', 'iPhone');

map.set('Brand', 'Apple');

map.set('Price', '$1000');

console.log(map.size)//=> 3

Accessing Elements in Map

The Map provides us with a .get() method to quickly get the value by passing the key as an argument in the method.

const map = new Map();

map.set('Name', 'iPhone');

map.set('Brand', 'Apple');

map.set('Price', '$1000');

console.log(map.get('Name')); //iPhone

console.log(map.get('Brand')); // Apple

But what if you want only the keys, values, or both key and value?

Map has .keys() ,.values() and.entries() respectively for achieving the same.

Using the same map from the code above,

console.log(map.keys());
// iterator {'Name','Brand',Price'}

console.log(map.values());
// iterator {'iPhone','Apple','$1000'}

console.log(map.entries());
//iterator {'Name':'iPhone','Brand':'Apple',Price':'$1000'}

Iterating over the map is also quite simple.

//with for-each
map.forEach((value, key) => {
   console.log(`${key} is ${value} years old!`);
});

// with for-of
for(const [key, value] of map) {
  console.log(`${key} : ${value}`);
}

Moreover, you can easily check if an element exists or not using .has() property and passing the key.

var map = new Map();
map.set('age',19);

console.log(map.has('age')) // true since 'age' key is present

Converting Object into a Map

If you decide to convert your object to a map, JavaScript has got you covered.

We have earlier used .entries() to get all the key-value pairs but this time we are gonna use the method on Object .

const myObject= {
  'Age': '25',
  'Gender': 'Male',
  'Nationality': 'Australian'
};

const myMap = new Map(Object.entries(myObject)); //object to map

const anotherObject = Object.fromEntries(myMap) // map to object

You can easily convert a map to an object as well as shown above.

To convert the map into an array we can use the Array.from(myMap) .

Map vs Array & Objects

The Map seems to solve a lot of shortcomings of the array and objects such as able to handle much more complex operations.

The Map is like a hybrid of array and objects. It has a size property like array and can store elements in a key-value pair format.

Besides this, it also provides methods to like .has() to check if an element exists or not which can save you a ton of time.

Moreover, it does not necessarily need the key to be of String type. You can even use an object as a key that can help you write better code.

You can a much more detailed guide here.

Final thoughts

While Array and Objects have become the de facto standard to store collections and key-value pair elements, with the introduction of Map and Set you can give your code an interesting approach.

Set and Map are the new standards offered by JavaScript for storing complex data structures.

Additionally, using these data structures also eliminates the need to use a third-party library like Lodash as these new data structures provide methods like .has() and .delete() by default.

Array and objects are not obsolete in any sense, however, using set and the map is surely a better way to handle data especially when building giant, complex applications.

Enjoyed this article? If so, get more similar content by **subscribing to Decoded, our YouTube channel!**

Did you find this article valuable?

Support Smart Dev Blogs by becoming a sponsor. Any amount is appreciated!