Javascript map array of objects to another array of objects





Hey guys in this short article, we will discuss map the array of objects to another array of objects using Javascript map() with several examples.

Introduction


In every programming language, it is very common that map the array objects to a different array modifying its values and keys. In javascript we can easily achieve this using map()

map() takes callback function as a parameter. A callback function that accepts up to three arguments.

  • value, which is nothing but the current value
  • index, which is nothing but the index of the current value, index always starts from 0, index is optional
  • array, which is nothing but the entire array, array is optional

map() calls the callback function one time for each element in the array and returns a new array.

Iterate through the array and return a new array


Consider the array of numbers, we will iterate through the array and return a new array, while returning we will multiply the values with another number.

const numbers = [1, 2, 3, 4, 5, 6];

const result = numbers.map(callback);

function callback(value, index, array) {
    return value * 2;
}

console.log(result);

Run the example:

PS C:\workspace\javascript-workspace> node app.js
[ 2, 4, 6, 8, 10, 12 ]

Iterate through the array of objects and return a new array


Consider the following employees array of objects, we will iterate through this array and return a new array of objects. We will modify the keys and values.

const employees = [
    {
        name: "Bushan",
        department: "IT",
        salary: 1000000
    },
    {
        name: "Bharath",
        department: "Marketing",
        salary: 800000
    },
    {
        name: "Chaitra",
        department: "Sales",
        salary: 700000
    }
];

const newEmployees = employees.map(value => ({
    EmpName: value.name,
    EmpDepartment: value.department,
    EmpSalary: Math.round(value.salary/12),
    EmpAnnualSalary: value.salary
}))

console.log(newEmployees);

Run the example:

PS C:\workspace\javascript-workspace> node app.js
[
  {
    EmpName: 'Bushan',
    EmpDepartment: 'IT',       
    EmpSalary: 83333,
    EmpAnnualSalary: 1000000   
  },
  {
    EmpName: 'Bharath',        
    EmpDepartment: 'Marketing',
    EmpSalary: 66667,
    EmpAnnualSalary: 800000
  },
  {
    EmpName: 'Chaitra',
    EmpDepartment: 'Sales',
    EmpSalary: 58333,
    EmpAnnualSalary: 700000
  }
]

We will return a new object with a new keys, EmpName, EmpDepartment, EmpSalary and EmpAnnualSalary

That’s it for this post, if you like this post, share this with your friends and colleagues or you can share this within your social media platform. Thanks, I will see you in our next post.



Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply