My goal is to efficiently convert the data retrieved from my firebase database into a format suitable for use with a SectionList.
I have successfully established a part of the data structure, but I am facing challenges in associating the data correctly.
The required format for the SectionList is as follows:
[
{
index: 0,
title: "Pan simple",
data: [
{
id: 0,
},
{
id: 1,
}
]
},
{
index: 1,
title: "Pan dulce",
data: [
{
id: 0,
}
]
}
]
The current format of the data received from my database is as shown below:
"storeName": {
products: {
'-Lo7D2Y8ZVEXnJb5LMvd': {
name: 'Pan de molde',
category: 'Molde'
},
'-Lo7C4HAkeE0cssxg9E-': {
name: 'Bollo de Hamburguresa',
category: 'Hamburguesa'
}
},
category: {
Molde: {
'-Lo7D2Y8ZVEXnJb5LMvd': true
},
Hamburguesa: {
'-Lo7C4HAkeE0cssxg9E-': true
}
}
}
In this structure, the "title" corresponds to the keys within the categories and the "data" refers to the objects under the products branch. I have implemented a function to fetch and transform this data:
export default (props, storeName) => {
firebase
.database()
.ref(`Store/${storeName}`)
.on("value", function(snapshot) {
if (snapshot.val() != null) {
var values = snapshot.val() || {};
var dataFormat = [];
var x = 0;
for (var i in values.category) {
var data = Object.assign({
data: [],
index: x,
category: i
});
dataFormat.push(data);
x++;
}
console.log("Data", dataFormat);
}
});
};
Currently, the output is
[
{ data: [], index: 0, category: 'Molde' },
{ data: [], index: 1, category: 'Hamburguesa' }
]
However, the desired output should be:
[
{
data: [
{
id: 'Lo7D2Y8ZVEXnJb5LMvd',
name: 'Pan de molde',
category: 'Molde'
}
],
index: 0,
category: 'Molde'
},
{
data: [
{
id: '-Lo7C4HAkeE0cssxg9E-',
name: 'Bollo de Hamburguresa',
category: 'Hamburguesa'
}
],
index: 1,
category: 'Hamburguesa'
}
]
How can I ensure that the appropriate data is assigned to each section?