Create Map function for objects (instead of arrays) - Nodejs map


NodeJS

Author: Steve Alila
Reviewer: Deepak Prasad

Object mapping enables you to handle data comfortably. However, the main challenge of implementing Nodejs map is that objects lack the native map method that arrays have.

You need to convert the object to an array and then apply the map function. It would be best to understand objects and higher-order functions before that.

Here is a quick overview of the Nodejs map on objects.

Store the data.

const data = { ... }

Convert the object to an array using Object.keys.

const objectToArray = Object.keys(data)

Now apply the map function on the array.

objectToArray.map( (key, index) => {target output} )

Apart from Object.keysYou could iterate over the object using the for-in loop and hasOwnProperty() method.

const data = { ... }
for(let key in data){
    if(data.hasOwnProperty(key)) {
       <target output>
    } 
}

The above ways to map function for objects (instead of arrays) modify the original array. If you want only to change a copy of the object instead, you can do that through their entries, as you will see in the examples section.

Let's dive into a deeper explanation of Nodejs map.

 

Understand Objects before applying Nodejs maps

The first step to Nodejs mapping is understanding objects.

There are two main data groups in JavaScript: primitives and references.

Primitives are the simplest data units. They include strings, numbers, Booleans, symbols, null and undefined. A group of primitives results is called a reference.

Examples of references are arrays, functions, and objects.

An array is an indexed data structure. That makes it easy to loop through its elements. A function is a reusable block of code accomplishing a specific task. An object is a key-value pair data structure.

NOTE:
reassigning a primitive creates its copy while reassigning a reference modifies the original object value.

Technically, every JavaScript data type is an object. Every object, in turn, has a constructor property that references the function that created the object.

For example, you can create a string, number, or Boolean from its constructor.

const str = new String('Map function for objects (instead of arrays) -> Nodejs map')
const num1 = new Number(23)
const isTrue = new Boolean(true)

// print result
console.log(str, num1, isTrue)
console.log(typeof str, typeof num1, typeof isTrue)

​// result
[String: 'Map function for objects (instead of arrays) -> Nodejs map'] [Number: 23] [Boolean: true]
object object object

A constructor function creates an instance of a class. And an instance of a class is an object.

The constructor's first letter starts with a capital letter, unlike a regular function. The new keyword instantiates an object from the constructor. The String, Number, Boolean and Symbol constructors are built-in to JavaScript.

We can also create custom constructors.

function Pet(name, age, color){
  this.name = name
  this.age = age
  this.color = color
}

We then instantiate the constructor using the new keyword.

const dog1 = new Pet('Jane Doe', 2, beige)

The new keyword takes the instance and passes it as the first parameter to the constructor function. this keyword then references the empty object, allowing the constructor function to append attributes to it.

 

The significance of Constructors in Nodejs map

The advantage of working with JavaScript objects is that, unlike most object-oriented programming languages, dynamic JavaScript objects relieve you of the burden of constantly defining properties to a static class. Instead, you can create an empty object and fill it with properties when needed.

The dynamic property of the objects makes JavaScript powerful in client-server interactions and Nodejs maps. For instance, the client sends the user object to the server. The server, in turn, appends more properties like a token to the user object.

 

The role of prototypes in Nodejs map

Like constructors, every object in JavaScript has a built-in prototype, a mechanic allowing the language to inherit features from one object to another.

The prototype has a data type of object. Prototypes can work with constructors or become constructor alternatives. Here are typical prototypes used in Nodejs maps on objects.

Prototype Role
create make a new object from a literal.
keys return an array with string elements corresponding to the enumerable properties
values return an array of enumerable properties in the specified order
entries return an array of enumerable properties key-value pair [key, value] that get passed as a parameter while maintaining the parsing of the arguments.
fromEntries return an object from the passed key-value pairs.

 

Now that you understand the role of prototypes in Nodejs map, let's dive into another concept: higher-order functions and Nodejs map.

 

The concept of higher-order functions and Nodejs map on objects

This section focuses on the origin and significance of the map function in objects.

There are two main functions in JavaScript: first-class and higher-order functions. The main difference between first-class and higher-order functions is that higher functions either return a function or take in a function as an argument. The passed function is known as a callback function.

ECMAScript created particular higher-order functions to manipulate arrays. Examples of such functions are reduce, fill, forEach, filter, and map.

The map function runs a callback function on each array element. It then outputs a new array returned from the callback function. To map objects instead of arrays, you have to convert them to arrays because objects are not iterable.

You can do the conversion on the browser side. But when you don't care about cross-browser compatibilities, you should run JavaScript on Node. That result of Nodejs + object map is Nodejs map, as illustrated in the following examples.

 

Example-1: Nodejs map an object instead of an array

Assume we have an object storing users of a web application. One of the users is Adi, who is 27 years old. He is an admin, has written 9 blogs, and has 5 years of experience in blogging.

const users = { username: 'Adi', age: 27, role: 'Admin', blogs: 9, experienceYears: 5 }

Say we want to increment the age, blogs, and years of experience by 2. We can do that as follows.

Create a file.

touch main.js

Open the main.js file using a code editor. Next, open the file and store the target object portion.

const objectToMap = { age: 27, blogs: 9, experienceYears: 5 }

Now generate an array from the object.

const arrayFromObj = Object.keys(objectToMap)

And apply the map function to the array.

arrayFromObj.map( (key, index) => console.log(objectToMap[key] += 2))

Running the file on the terminal returns an output with each number incremented by 2.

Nodejs map

 

Example-2: Map function for objects using the for-in loop

Alternatively, you could iterate over the object using the for-in loop.

const objectToMap = { age: 27, blogs: 9, experienceYears: 5 }

for(let key in objectToMap){
    if(objectToMap.hasOwnProperty(key)) console.log(objectToMap[key] += 2)
}

Create Map function for objects (instead of arrays) - Nodejs map

 

Example-3: Map function for objects without modifying the original object

The problem with the above Nodejs map methods is they change the original object.

Object.keys():

Create Map function for objects (instead of arrays) - Nodejs map

 

For-in loops:

Create Map function for objects (instead of arrays) - Nodejs map

The solution is to create an array from the object's copy and modify it before reconverting the modified array to an object.

const objectToMap = { age: 27, blogs: 9, experienceYears: 5 }

const mapObject = (obj, fn) => {
  // convert the Array back to an Object
  return Object.fromEntries(
    Object
      .entries(obj)
      .map(fn)
  )
}

// Convert the Object into a mappable nested Array
const theNewObject = mapObject(objectToMap, ([key, value]) => ([key, value+2]))
console.log(theNewObject)

The result is

{ age: 29, blogs: 11, experienceYears: 7 }

and the best part is that this time around, the original object does not get altered.

Create Map function for objects (instead of arrays) - Nodejs map

 

Conclusion

Even though there is no native map function for objects, you can achieve a Nodejs map on objects by understanding object behaviors, constructors, and prototypes. You can then convert the object into an array, apply the map function to it and convert the array to an object.

 

Steve Alila

Steve Alila

He specializes in web design, WordPress development, and data analysis, with proficiency in Python, JavaScript, and data extraction tools. Additionally, he excels in web API development, AI integration, and data presentation using Matplotlib and Plotly. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment