I've been struggling with creating an object using reduce from a nested array. The task is to generate a new object with keys named _uid and values matching the initialValue from the objects that contain both properties. I have written a function that can iterate through the nested arrays but I am facing difficulty in returning the new object with all the extracted properties. I attempted to use shallow and deep copy methods to clone the accumulator, but without success. Is there anyone who could assist me?
This is the structure of the nested array:
export const formData = [
{
component: 'page',
label: 'Page 1',
_uid: '0c946643-5a83-4545-baea-055b27b51e8a',
fields: [
{
component: 'field_group',
label: 'Name',
_uid: 'eb169f76-4cd9-4513-b673-87c5c7d27e02',
fields: [
{
component: 'text',
label: 'First Name',
initialValue: '2345432',
type: 'text',
_uid: '5b9b79d2-32f2-42a1-b89f-203dfc0b6b98',
},
{
component: 'text',
label: 'Last Name',
initialValue: '2345432',
type: 'text',
_uid: '6eff3638-80a7-4427-b07b-4c1be1c6b186',
},
],
},
...
],
},
...
]
The logic behind the function:
function getInitialValues(formData = []) {
return Array.from(formData).reduce((acc, currentValue, idx) => {
const arrayOfStrings = ['page', 'field_group', 'options']
const str = currentValue.component
const found = arrayOfStrings.find((v) => str === v)
if (found) {
// console.log('entered', currentValue)
getInitialValues(currentValue?.fields)
return acc
}
if (
(currentValue.component === 'text' || currentValue.component === 'select') &&
currentValue.label === 'Conditional Field'
) {
acc[currentValue._uid] = currentValue?.initialValue
return acc
}
return acc
}, {})
}
The expected outcome should resemble this for all unique _uids that have initialValues assigned:
{
5b9b79d2-32f2-42a1-b89f-203dfc0b6b98: '2345432',
5b9b79d2-32f2-42a1-b89f-203dfc0b6b97: '2345431',
5b9b79d2-32f2-42a1-b89f-203dfc0b6b96: '2345430',
}