Resolved: How to reconstruct array of objects based on duplicate keys? 0 By Isaac Tonny on 17/06/2022 Issue Share Facebook Twitter LinkedIn Question: I’m getting an array object that looks like this. My goal is to combine or merge them based on duplicate keys. documents: [ { image: 'sample image 1', id_side: 'Front', type: 'Passport' }, { image: 'sample image 2', id_side: 'Back', type: 'Passport' }, { image: 'sample image 3', id_side: 'Back', type: 'License' } ] How can I arrange it to look like this? documents: [ { documentType: 'Passport', requiredDocs: [ { image: 'sample image 1', id_side: 'Front', type: 'Passport' }, { image: 'sample image 2', id_side: 'Back', type: 'Passport' } ] }, { documentType: 'License', requiredDocs: [ { image: 'sample image 3', id_side: 'Back', type: 'License' } ] } ] I have found a similar question but I can’t seem to make it work in my case. See the similar question in this link: How to merge/combine array of objects based on duplicate keys? Answer: You can achieve your output with this const documents = [ { image: "sample image 1", id_side: "Front", type: "Passport" }, { image: "sample image 2", id_side: "Back", type: "Passport" }, { image: "sample image 3", id_side: "Back", type: "License" } ]; let output = {}; documents.forEach((docs) => { if (output[docs.type]) { output[docs.type].requiredDocs.push(docs); } else { output[docs.type] = { documentType: docs.type, requiredDocs: [docs] }; } }); console.log(Object.values(output)); If you have better answer, please add a comment about this, thank you! arrays javascript javascript-objects object sorting