Is there a better or simplified approach to create an array which contains one object per objectid with an array of contacts that matches globalLkupRemoveContactReviewer by userid and then send each array which contains one object to the database in the form of
[
{
objectid: '222',
contacts: [
{ isdelete: '1', contactid: '1', associationid: '1968398' },
{ isdelete: '1', contactid: '2', associationid: '1968399' },
],
},
];
const globalLkupRemoveContactReviewer = [
{ objectid: 555, userid: '1', associationid: '1948874' },
{ objectid: 555, userid: '2', associationid: '1950833' },
];
//My Code:
var myStr = '111*1*1968397,222*1*1968398,222*2*1968399,333*2*1968401,333*4*1968402,333*1*19684034';
Object.values(
myStr
.split(',')
.map((item) => item.split('*'))
.map(([objectid, userid, associationid]) => ({
objectid,
userid,
associationid,
}))
.filter(
(item1) =>
!!globalLkupRemoveContactReviewer.find(
(item2) => item2.userid === item1.userid
)
)
.reduce((acc, { objectid, userid, associationid }) => {
(acc[objectid] ??= { objectid, contacts: [] }).contacts.push({
isdelete: '1',
contactid: userid,
associationid,
});
return acc;
}, {})
).forEach((item) => {
console.log([item]);
});
// Need result in this format to send to the database
// [ { "objectid": "111", "contacts": [ { "isdelete": "1", "contactid": "1", "associationid": "1968397" } ] } ]
// [ { "objectid": "222", "contacts": [ { "isdelete": "1", "contactid": "1", "associationid": "1968398" }, { "isdelete": "1", "contactid": "2", "associationid": "1968399" } ] } ]
// [ { "objectid": "333", "contacts": [ { "isdelete": "1", "contactid": "2", "associationid": "1968401" }, { "isdelete": "1", "contactid": "1", "associationid": "19684034" } ] } ]