I'm trying to iterate this block of code for displaying data in table. I want object arrays of equal length.
Hence, need to fill undefined values for respective keys to make array of objects uniform (same length)
Original Json
[
{
"toolName": "Alteryx",
"contacts": [
{
"contactPerson": "James clear",
"email": "[email protected]"
},
{
"contactPerson": "Paul Unger",
"email": "[email protected]"
}
]
},
{
"toolName": "Processes",
"contacts": [
{
"contactPerson": "naomi Unger",
"email": "[email protected]"
}
]
},
{
"toolName": "Alteryx Server",
"contacts": [
{
"contactPerson": "Avinash",
"email": "[email protected]"
},
{
"contactPerson": "Sowmia",
"email": "[email protected]"
}
]
}
]
Expectation json
[
{
"toolName": "Alteryx",
"contacts": [
{
"contactPerson": "James clear",
"email": "[email protected]"
},
{
"contactPerson": "Paul Unger",
"email": "[email protected]"
}
]
},
{
"toolName": "Processes",
"contacts": [
{
"contactPerson": "naomi Unger",
"email": "[email protected]"
},
{
"contactPerson": null,
"email": null
}
]
},
{
"toolName": "Alteryx Server",
"contacts": [
{
"contactPerson": "Avinash",
"email": "[email protected]"
},
{
"contactPerson": "Sowmia",
"email": "[email protected]"
}
]
}
]
Tried this, but not working
let max = 0;
const masterArray = res?.data?.tools?.map((obj) => {
obj.contacts.forEach((ele, ind) => {
if(max <= ind){
max = ind;
}
for(let i = 0 ; i< max; i++){
if (ele !== undefined) return ele;
return { ...ele,
contactPerson: '',
email: '',
}
}
});
});
How to fill null/undefined values to handle error.
const contact = el.contacts[i] ?? {contactPerson: null, email: null};