I have a huge array of objects, and I want to divide it up to 4 sections so that I could display them much better on my UI.
Here are the array contents, and let's say this contains up to 20 objects, so my goal is to have 4 different arrays that will be containing 5 objects each.
let attributes = [
{
"FIELDTYPE": "SELECT",
"ATTRNAME": "Title",
"ATTRNAMEID": "title",
"ATTRID": 1
},
{
"FIELDTYPE": "SELECT",
"ATTRNAME": "Author",
"ATTRNAMEID": "author",
"ATTRID": 2
},
{
... //up to 20 more attributes
}
]
I tried to map it like this, but it's not really giving me what I needed
let bookAttributeFields_0;
let bookAttributeFields_1;
let bookAttributeFields_2;
let bookAttributeFields_3;
let bookAttributeFields = attributes.map((attr, i) => {
switch (i % 4) {
case 1:
let fields_1 = {
name: attr.ATTRNAMEID,
type: attr.FIELDTYPE,
label: attr.ATTRNAME
}
bookAttributeFields_0 =
{
...bookAttributeFields_0,
fields_1
}
break;
case 2:
let fields_2 = {
name: attr.ATTRNAMEID,
type: attr.FIELDTYPE,
label: attr.ATTRNAME
}
bookAttributeFields_1=
{
...bookAttributeFields_1,
fields_2
}
break;
case 3:
let fields_3 = {
name: attr.ATTRNAMEID,
type: attr.FIELDTYPE,
label: attr.ATTRNAME
}
bookAttributeFields_2=
{
...bookAttributeFields_2,
fields_3
}
break;
case 0:
let fields_4 = {
name: attr.ATTRNAMEID,
type: attr.FIELDTYPE,
label: attr.ATTRNAME
}
bookAttributeFields_3=
{
...bookAttributeFields_3,
fields_4
}
break;
default:
//nothing
break;
}
return {
bookAttributeFields_0: bookAttributeFields_0,
bookAttributeFields_1: bookAttributeFields_1,
bookAttributeFields_2: bookAttributeFields_2,
bookAttributeFields_3: bookAttributeFields_3
}
})
This is how I intend to use the 4 new arrays to be displayed.
return <>
< Grid container spacing={2} >
<Grid item xs={3}>
{data.bookAttributeFields.map((field)=>{
return <Fields fields={field.bookAttributeFields_0} />
})}
</Grid>
<Grid item xs={3}>
{data.bookAttributeFields.map((field)=>{
return <Fields fields={field.bookAttributeFields_1} />
})}
</Grid>
<Grid item xs={3}>
{data.bookAttributeFields.map((field)=>{
return <Fields fields={field.bookAttributeFields_2} />
})}
</Grid>
<Grid item xs={3}>
{data.bookAttributeFields.map((field)=>{
return <Fields fields={field.bookAttributeFields_3} />
})}
</Grid>
</Grid >
</>
slice()might help, I don't think I ever used it so not sure. Although for the new array sizes, I'm worried that the exact array size for the new arrays are not fixed, and there would be scenarios where other one array would have 5 objects while others have 4 etc...