SubhanUllah Posted October 19, 2022 Report Share Posted October 19, 2022 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
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.