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?
CodePudding user response:
Use reduce()
to create an accumulation object, and then map()
the entries of that object to your desired output format:
const data = [{
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'
}];
const result = Object.entries(data.reduce((a, v) => ({
...a,
[v.type]: [...a[v.type] || [], v]
}), {})).map(([documentType, requiredDocs]) => ({
documentType,
requiredDocs
}));
console.log(result);
CodePudding user response:
const obj={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 types = obj.documents.reduce((a, { type, ...r }) => {
a[type] = a[type] || [];
a[type].push({ type, ...r });
return a;
}, {});
let result = Object.entries(types).map(([ documentType, requiredDocs ]) => ({ documentType, requiredDocs }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: auto; }