Created
July 12, 2017 19:22
-
-
Save KinoAR/36311a13ea8edf61369bd14908c3b172 to your computer and use it in GitHub Desktop.
An example of using for loop and map as a comparison.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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