DMDJ
DMDJ

Reputation: 407

array.map() : Return array instead of object (JavaScript)

I'm still a newbie with javascript. I'm facing a problem with mapping an array. I don't know how to return the an array with objects.

This is the initial array:

array1 = [{firstName: "Harry"},
          {lastName: "Potter"}];

When i do array1.map, it returns:

array1 = ["Potter"];

I want to make array1 to be like this after mapping the lastName:

array1 = [{lastName: "Potter"}];

Upvotes: 1

Views: 4244

Answers (2)

Saurabh Agrawal
Saurabh Agrawal

Reputation: 7739

As per the docs:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

It creates new array and returns it.

Upvotes: 0

Tân
Tân

Reputation: 1

You can use filter function instead

array1 = [{firstName: "Harry"},
          {lastName: "Potter"}];
          
console.log(array1.filter(x => x.lastName === "Potter"));

Upvotes: 2

Related Questions