Given the following two json objects, where files represents an array of directories and colourCodes represents a mapping from a colour to status, I want to process the array of files (which is actually a list of directories) to determine a directory structure. In each file the folderColorRgb maps to a status (the status can be looked up from the colourCodes constant - if the colour doesn't exist in colourCodes then the status is Not covered).
const colourCodes = {
'#4986e7': 'Covered 100%',
'#f83a22': 'Covered - weak',
}
const files = [
{
id: '1nn7_JlbwQCxyz7qecqEtbWvY4C9Q2S3M',
name: 'cell biology',
parents: [ '1YewXh1WkIVIxOuHTV9acYG7WDE55EnPR' ],
},
{
id: '1bcNxav7kq--E1Qabu3tcXk9DxvRdCcgR',
name: 'ecology',
parents: [ '1YewXh1WkIVIxOuHTV9acYG7WDE55EnPR' ],
folderColorRgb: '#4986e7'
},
{
id: '1MmkaP5xveClf6BfrhjHyYv4Q_Vaq1vf_',
name: 'infection and response',
parents: [ '1YewXh1WkIVIxOuHTV9acYG7WDE55EnPR' ],
folderColorRgb: '#8f8f8f'
},
{
id: '1YewXh1WkIVIxOuHTV9acYG7WDE55EnPR',
name: 'biology',
parents: [ '1WVm7S1fw8Neg7FM80QNxcMWvVc_w_Jt2' ],
folderColorRgb: '#16a765'
},
{
id: '1WVm7S1fw8Neg7FM80QNxcMWvVc_w_Jt2',
name: 'science',
parents: [ '0AF24wY_V36dlUk9PVA' ],
folderColorRgb: '#a47ae2'
},
{
id: 'physics-id',
name: 'physics',
parents: [ '1WVm7S1fw8Neg7FM80QNxcMWvVc_w_Jt2' ],
folderColorRgb: '#16a765'
},
{
id: 'electricity-id',
name: 'electricity',
parents: [ 'physics-id' ],
folderColorRgb: '#f83a22'
},
]
The result I want to achieve is as follows:
{
science: {
biology: {
'cell biology': { status: 'Not covered' },
ecology: { status: 'Covered 100%' },
'infection and response': { status: 'Not covered' },
},
physics: { electricity: { status: 'Covered - weak' } },
},
}
So it's the folder structure of the files array represented in JSON. You can make the following assumptions
- The
parentsarray of each file will always contain oneparentId, that is the link to the parent folder. - All
parentId'sexist as aidin the file array - except for the top level directory (e.g. science in this case, the parentId for science does not exist infiles.
Anyone know of a nice way to achieve this?