Modify Values in an Array with Map

InstructorShane Osbourne

Share this video with your friends

Send Tweet

Map is one of the most useful array methods. It creates a new array with the exact same number of items as the source and can be used to modify values, change their type, add fields to objects, simplify objects etc. In this lesson we focus on practical use-cases for map & see it in conjunction with other array methods.

Vamshi
~ 8 years ago

In the example here, we wanted to add lastname property to each object. const items = [ { firstname: 'Shane', lastname: 'Osbourne' }, { firstname: 'Sally', lastname: 'Osbourne' }, { firstname: 'Ben', lastname: 'Barker' } ];

Now what if I dont know how my objects look like from the API call, and lets say each object is not too identical, for example, const items = [ { firstname: 'Shane', lastname: 'Osbourne', income: '200000' }, { firstname: 'Sally', lastname: 'Osbourne', kids: 2 }, { firstname: 'Ben', lastname: 'Barker' } ];

Is there a way we can still add a property to the object, like const items = [ { firstname: 'Shane', lastname: 'Osbourne', income: '200000', status: good }, { firstname: 'Sally', lastname: 'Osbourne', kids: 2, status: good }, { firstname: 'Ben', lastname: 'Barker', status: good } ];

Like that using map? Thank you

Michael
~ 6 years ago

Hey Shane! What editor or IDE are you using for these videos? It looks like Sublime Text, but not sure how you are getting the output view. Thanks!