SubhanUllah Posted October 19, 2022 Report 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.
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now