My array consists of multiple objects:
const items = [{ search_type: 'environment',
search_code: 'TBA_ENVIRONMENT00002',
asset_code: 'ASSET00002' },
{ search_type: 'job',
search_code: 'TBA_JOB00002',
asset_code: 'ASSET00002' },
{ search_type: 'environment',
search_code: 'TBA_ENVIRONMENT00002',
asset_code: 'ASSET00004' },
{ search_type: 'job',
search_code: 'TBA_JOB00002',
asset_code: 'ASSET00004' },
{ search_type: 'job',
search_code: 'TBA_JOB00003',
asset_code: 'ASSET00004' },
{ search_type: 'scene',
search_code: 'TBA_SCENE00006',
asset_code: 'ASSET00002' },
];
I wish to transform it into a structure like this:
{
ASSET00002: {
environment:["TBA_ENVIRONMENT00002"],
job:["TBA_JOB00002"],
scene:["TBA_SCENE00006"]
},
ASSET00004: {
environment:["TBA_ENVIRONMENT00002"],
job:["TBA_JOB00002","TBA_JOB00003"]
},
}
Using the following Reduce function logic:
const result = items.reduce((acc, item) => {
const { search_type, search_code, asset_code } = item;
return {
...acc,
[asset_code]: {
...acc[asset_code], [search_type]: [search_code]
},
};
}, {});
The outcome I'm currently getting is:
{
ASSET00002: {
environment:["TBA_ENVIRONMENT00002"],
job:["TBA_JOB00002"],
scene:["TBA_SCENE00006"]
},
ASSET00004: {
environment:["TBA_ENVIRONMENT00002"],
job:["TBA_JOB00003"]
},
}
Based on "ASSET00004"-> "job", I expect an array with two values but only receiving one. I'm aware there may be missing elements in my code, struggling to figure out how to properly add values to the array. Appreciate any assistance provided.