Skip to content

Instantly share code, notes, and snippets.

@RedGhoul
Last active March 11, 2019 18:20
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 RedGhoul/d31d5603346da88d69da8af4123cb72c to your computer and use it in GitHub Desktop.
Save RedGhoul/d31d5603346da88d69da8af4123cb72c to your computer and use it in GitHub Desktop.
MapsInJS
// Array you wanna do the operation on
const peopleArray = [ {Name: "Tim", BankBalance: 10},
{Name: "Leo", BankBalance: 20},
{Name: "Sam", BankBalance: 30} ];
// calling the Map function and having it return its value into
// reformattedArray. Where "obj" represents each object in the
// peopleArray
let reformattedArray = peopleArray.map((obj) =>{
let newObj = {};
newObj.Name = "Mr." + obj.Name;
newObj.BankBalance = obj.BankBalance * 1000;
return newObj;
});
console.log(reformattedArray);
// "reformattedArray" is now: [ { Name: 'Mr.Tim', BankBalance: 10000 },
// { Name: 'Mr.Leo', BankBalance: 20000 },
// { Name: 'Mr.Sam', BankBalance: 30000 } ]
// you can also get another parameter that is passed in. Known as the index
// of the object in the old array (peopleArray in this case)
reformattedArray = peopleArray.map((obj, index) =>{
let newObj = {};
newObj.MyIndex = index;
newObj.Name = "Mr." + obj.Name;
newObj.BankBalance = obj.BankBalance * 1000;
return newObj;
});
console.log(reformattedArray);
// "reformattedArray" is now:[ { MyIndex: 0, Name: 'Mr.Tim', BankBalance: 10000 },
// { MyIndex: 1, Name: 'Mr.Leo', BankBalance: 20000 },
// { MyIndex: 2, Name: 'Mr.Sam', BankBalance: 30000 } ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment