Array.prototype.map()
: Returns a new array with the results of calling a provided function on every element in the original array.
The following code example takes an array of persons and creates a new array containing persons with a 'fullName' property
var personsArray = [
{
id: 1,
firstName: "Malcom",
lastName: "Reynolds"
}, {
id: 2,
firstName: "Kaylee",
lastName: "Frye"
}, {
id: 3,
firstName: "Jayne",
lastName: "Cobb"
}
];
// Returns a new array of objects made up of full names.
var reformatPersons = function(persons) {
return persons.map(function(person) {
// create a new object to store full name.
var newObj = {};
newObj["fullName"] = person.firstName + " " + person.lastName;
// return our new object.
return newObj;
});
};
We can now call reformatPersons(personsArray)
and received a new array of just the full names of each person.
var fullNameArray = reformatPersons(personsArray);
console.log(fullNameArray);
/// Output
[
{ fullName: "Malcom Reynolds" },
{ fullName: "Kaylee Frye" },
{ fullName: "Jayne Cobb" }
]
personsArray
and its contents remains unchanged.
console.log(personsArray);
/// Output
[
{
firstName: "Malcom",
id: 1,
lastName: "Reynolds"
}, {
firstName: "Kaylee",
id: 2,
lastName: "Frye"
}, {
firstName: "Jayne",
id: 3,
lastName: "Cobb"
}
]