How to use Array.map() Method In Javascript

This method uses the Array.map() method to create the new array by swapping the values of each key present in the object. The output consists of the swapped values printed using the log() function.

Example: The below code uses the Array.map() method to swap the array of object values using JavaScript.

Javascript




// arr of objs
let arr = [{a: 1, b: 2}, {a: 3, b: 4}];
console.log("Before Swapping: ", arr);
// swapping values using map()
arr = arr.map(obj => ({a: obj.b, b: obj.a}));
// output arr
console.log("After Swapping: ", arr);


Output

Before Swapping:  [ { a: 1, b: 2 }, { a: 3, b: 4 } ]
After Swapping:  [ { a: 2, b: 1 }, { a: 4, b: 3 } ]

How to Swap Array Object Values in JavaScript ?

We have given the array of objects, and our task is to swap the values of the object keys present in the array of objects. Below is an example for a better understanding of the problem statement.

Example:

Input: arr = [{a: 1, b: 2}, {a:3, b: 4}]
Output: [ { a: 2, b: 1 }, { a: 4, b: 3 } ]
Explnation: The values of the object keys a and b before swapping
were 1 and 2 respectively. But after swapping they gets interchanged.

Table of Content

  • Using Destructuring Assignment
  • Using Temp Variable
  • Using Array.map() Method
  • Using Array.forEach() Method

Similar Reads

Using Destructuring Assignment

This method uses the for loop to iterate over the array of objects, swapping the values of ‘a’ and ‘b’ properties in each object using the destructuring assignment. Once the swapping is done, we print the swapped values using the log() function....

Using Temp Variable

...

Using Array.map() Method

This method uses the temporary variable to swap the values of the array of objects. The loop is used to go over the array of objects, swapping the values of ‘a’ and ‘b‘ properties in each object using the temp variable....

Using Array.forEach() Method

...