I have a bit of complex data to work with. I am building an application with Nodejs and Nextjs. I am pulling data from my database that has this type of structure:
const response = {
item1: 'someItem',
item2: 'someitem2',
packages: [
{
packagaA: 'packageA',
quantity: 3
},
{
packagaA: 'packageB',
quantity: 1
},
{
packagaA: 'packageC',
quantity: 2
},
questions: [
{
question1: 'question1',
},
{
question2: 'question2',
},
{
question3: 'question3',
}
]
]
}
This is just a sample of the response structure. I would like to render this in frontend this way:
For packages
which is an array, I want to render it based on the number of package
quantity. So, if packageA
has 3 quantities
, using map
method, packageA
would be rendered 3 times, packageB
would be rendered 1 and packageC
would be rendered 2 times. This I have achieved.
The challenge is rendering question and updating accordingly. If you take a look at question field, it is an array. So, I would like question to be rendered per package item and should be rendered based on the quantity of the package. For instance, packageA
appeared 3 times, this means that the question would be rendered 3 times too. These questions would take answers from users from input
tag. How can I make these input tag responses unique? How do I handle such complex data structure?
To render the packages, I created a custom array that replicates the package object based on their quantity and formed a new array like this:
useEffect(()=>{
let tempObjArray:{itemName: string}[] = [];
const filterArray = response?.packages?.filter((item, index) => item?.itemType === 'package_order');
filterArray?.map((item, index)=>{
for(let i = 0; i < Number(item?.orderedQuantity); i++){
tempObjArray.push({itemName: item?.orderedItemName});
}
});
setTemporaryPackageData(tempObjArray)
}, []);
return(
<div>
{
temporaryPackageData?.map((item, index)=>(
<p>{item?.itemName}</p>
))
}
</div>
)
This renders the packages based on their quantity. So, if the first package has 3 quantities, it would render 3 times. The challenge now is how to make each of them rendered to have their own questions and for users to uniquely respond to these questions. I have been able to get this done but I am not able to get users respond to each of these questions uniquely.