Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An example of using for loop and map as a comparison.
/* Map Example - Adding a property Business */
const employeeList = [
{ name: 'Tom', job: 'Programmer' },
{ name: 'Sam', job: 'Chef' },
{ name: 'Jennifer', job: 'Digital Artist' }
];
//Create Second List to maintain original contents
const employeeList2 = JSON.parse(JSON.stringify(employeeList));
const business = 'Sun Corp';
/* For Loop */
//Create new list to contain elements
const newEmployeeList = [];
for(let i = 0; i < employeeList.length; i++) {
const copy = JSON.parse(JSON.stringify(employeeList[i]));
copy.business = business;
newEmployeeList.push(copy);
}
console.log(employeeList);
console.log(newEmployeeList);
/* Map */
//List instantly created by map
const newEmployeeList2 = employeeList2.map((element) => {
const copy = JSON.parse(JSON.stringify(element));
copy.business = business;
return copy;
});
console.log(employeeList2);
console.log(newEmployeeList2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment