Skip to content

JavaScript map return array of objects | Code

  • by

Using the combination of flatMap, map and destructuring can do a JavaScript map return array of objects.

JavaScript map return array of objects

Simple example code returns a simple object only with the data that selected in the second map object.

<!DOCTYPE html>
<html>
<body>
  <script >
    const responses = [
    {
      data: {
        id: "123",
        capacity: 20,
        childNested: [{ date: { name: "foo1" } }, { date: { name: "foo2" } }],
      },
    },
    {
      data: {
        id: "456",
        capacity: 40,
        childNested: [{ date: { name: "bar" } }],
      },
    },
    ];

    const output = responses.flatMap(({ data }) =>
      data.childNested.map(({ date: { name } }) => ({
        id: data.id,
        name: data.capacity,
        date: name,
      }))
      );
    console.log(responses)
    console.log(output)
  </script>
</body>
</html>

Output:

JavaScript map return array of objects

Return an array of objects with new keys

<script >
    var arr = [{
      id: 1,
      name: 'foo'
    }, {
      id: 2,
      name: 'bar'
    }];

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

</script>

Output:


[
  {
    "value": 1,
    "text": "bill"
  },
  {
    "value": 2,
    "text": "ted"
  }
]

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this Js map 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

Your email address will not be published. Required fields are marked *