From the HTML structure, I have generated the following array:
const sort = [{ section_id: 'b', children: ['2'] }, { section_id: 'a', children: ['1', '3'] }]
Each object in this array represents a section, where children is an array of content ids belonging to that section.
There is also a product object:
const product = {
id: 'asd',
title: 'product title',
sections: [
{ id: 'a', title: 'section with id a', contents: [{ id: '1' }] },
{ id: 'b', title: 'section with id b', contents: [{ id: '2' }, { id: '3' }] }
]
}
The goal is to "re-create" the product object based on data coming from sort. The expected result would be as follows:
const sortedProduct = {
id: 'asd',
title: 'product title',
sections: [
{ id: 'b', title: 'section with id b', contents: [{ id: '2' }] },
{ id: 'a', title: 'section with id a', contents: [{ id: '1' }, { id: '3' }] }
]
}
A function has been written to achieve this, but the output is not as expected. Please provide guidance on what might be incorrect in the implementation.
const SrtProduct = () => {
const sort = serializeSections() // returns array as in example
let sortedProduct = {}
sortedProduct.sections = []
const emptySection = {
_id: '',
contents: [],
title: ''
}
Object.keys($productStore).forEach(key => {
if(key !== 'sections') sortedProduct[key] = product[key]
})
sort.forEach((section, index) => {
sortedProduct.sections[index] = emptySection
let pozycja = getIndex(product.sections, section.id)
Object.keys(product.sections[index]).forEach(key => {
if(key !== 'contents') sortedProduct.sections[index][key] = product.sections[pozycja][key]
})
if(section.children.length > 0) section.children.forEach((content_id, ind) => {
let poz = getContentIndex(product.sections, content_id)
let tmp = sortedProduct.sections[index]
tmp.contents.push(product.sections[poz[0]].contents[poz[1]])
sortedProduct.sections[index] = tmp
})
})
return sortedProduct
}
The current output is:
...
sections: [
{ id: 'a', title: 'section with id a', contents: [{id: '2'}, {id: '1'}, {id: '3'}] },
{ id: 'b', title: 'section with id b', contents: [{id: '2'}, {id: '1'}, {id: '3'}] }
]
The helper functions getIndex and getContentIndex are functioning correctly.
getIndex returns the position in the array where a section with the given id is found. For example, getIndex(product.sections, 'b') would return 1
getContentIndex For instance, getContentIndex(product.sections, '2') would return [1,0] (section position 1, content position 0)
Input: product, sort
Output The sortedProduct which rearranges the sections and contents according to the information from sort