Skip to content

Instantly share code, notes, and snippets.

@KinoAR
Created July 12, 2017 19:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KinoAR/36311a13ea8edf61369bd14908c3b172 to your computer and use it in GitHub Desktop.
Save KinoAR/36311a13ea8edf61369bd14908c3b172 to your computer and use it in GitHub Desktop.
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