Skip to content

JavaScript map array of objects | Example code

  • by

Using the map function you can create an array of objects. The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

JavaScript map array of objects

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    var arr = [{
      id: 1,
      name: 'bill'
    }, {
      id: 2,
      name: 'ted'
    }]

    var res = arr.map(person => ({ value: person.id, text: person.name }));

    console.log(res)

  </script>
</body>
</html>

Output:

JavaScript map array of objects

How To Use .map() to Iterate Through Array Items in JavaScript

Answer: The map() can be used to iterate through objects in an array and, in a similar fashion to traditional arrays, modify the content of each individual object and return a new array. This modification is done based on what is returned in the callback function.


<script>
   const myUsers = [
   { name: 'Shark', likes: 'ocean' },
   { name: 'Turtle', likes: 'pond' },
   { name: 'Otter', likes: 'fish biscuits' }
   ]

   const usersByLikes = myUsers.map(item => {
    const container = {};

    container[item.name] = item.likes;
    container.age = item.name.length * 5;

    return container;
  })

   console.log(usersByLikes);
</script>

Output:

Iterate Through Array Items in JavaScript

Do comment if you have any doubts or suggestions on this JS array of objects topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading