Jump to content

How to map an array of objects in JavaScript?


SubhanUllah

Recommended Posts

Code sample using the reduce function:

const myArrayOfObjects = [ 
    { myKey: 1, data: 'some data' }, 
    { myKey: 2, data: 'some data' }, 
    { myKey: 3, data: 'some data' }, 
    { myKey: 4, data: 'some data' }, 
    { myKey: 5, data: 'some data' }, 
    { myKey: 6, data: 'some data' }, 
    { myKey: 7, data: 'some data' }, 
]; 
 
const myMap = myArrayOfObjects.reduce( 
    (accumulator, currentObject) => ({ 
        ...accumulator, 
        [currentObject.myKey]: currentObject, 
    }), 
    {} 
); 
 
console.log(myMap); 
 
// output: 
// { 
//     '1': { myKey: 1, data: 'some data' }, 
//     '2': { myKey: 2, data: 'some data' }, 
//     '3': { myKey: 3, data: 'some data' }, 
//     '4': { myKey: 4, data: 'some data' }, 
//     '5': { myKey: 5, data: 'some data' }, 
//     '6': { myKey: 6, data: 'some data' }, 
//     '7': { myKey: 7, data: 'some data' } 
//   } 

Repeated keys will be overwritten, so take into account that if you have repeated keys only the last one will remain.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...