Currently, I have a data mapping function that can take JSON data with up to four levels and transform it into a different format.
The input JSON format looks like this:
[{
"InventoryLevel2Id": "1234",
"InventoryLevel2Information": "Test Data",
"InventoryLevel2Name": "Test Data",
"InventoryLevel3s": [
{
"InventoryLevel3Id": "5678",
"InventoryLevel3Name": "Inner data at 1",
"InventoryLevel3Information": "Inner info at 1",
"InventoryLevel4s": [
{
"InventoryLevel4Id": "9101112",
"InventoryLevel4Name": "Inner data at 2",
"InventoryLevel4Information": "Inner info at 2",
"InventoryLevel5s": [
{
"InventoryLevel5Id": "131415",
"InventoryLevel5Name": "Inner data at 3",
"InventoryLevel5Information": "Inner info at 3"
}
]
}
]
}
]
}]
The output JSON format should be transformed to:
[{
label1: 'TestData',
label2: "Test data",
uniquieId: "1234",
innerState: {
data : {
label1: 'Inner data at 1',
label2: "Inner info at 1",
uniquieId: "5678",
innerState: {
data: {
label1: 'Inner data at 2',
label2: "Inner info at 2",
uniquieId: "9101112",
innerState: {
data: {
label1: 'Inner data at 3',
label2: "Inner info at 4",
uniquieId: "131415"
}
}
}
}
}
}
}]
To enhance the efficiency and reduce repetitive calls to the mapper function, I am considering creating a recursive function that will handle all mapping for multiple levels.
const recursiveDataMapper = (inputData) => {
const mappedData = inputData?.map((a) => ({
label1: a.InventoryLevel2Name,
label2: a.InventoryLevel2Information,
uniquieId: a.InventoryLevel2Id,
innerState: {
data: a.InventoryLevel3s?.map((b) => ({
label1: b.InventoryLevel3Name,
label2: b.InventoryLevel3Information,
uniquieId: b.InventoryLevel3Id,
innerState: {
data: b.InventoryLevel4s?.map((c) => ({
label1: c.InventoryLevel4Name,
label2: c.InventoryLevel4Information,
uniquieId: c.InventoryLevel4Id,
innerState: {
data: c.InventoryLevel5s?.map((d) => ({
label1: d.InventoryLevel5Name,
label2: d.InventoryLevel5Information,
uniquieId: d.InventoryLevel5Id
}))
}
}))
}
}))
}
}));
return mappedData;
};
While trying to optimize the mapping process, my initial attempt at a mapper function only covers up until InventoryLevel3s. It lacks completeness and could benefit from further improvement.
const tryRecursiveDataMapper = (inputData) => {
const mappedData = inputData?.map((a) =>
helper(
a,
"InventoryLevel2Name",
"InventoryLevel2Information",
"InventoryLevel3Id",
"InventoryLevel3s"
)
);
return mappedData;
};
const helper = (entity, field1, field2, uniquieId, childEntityName) => {
if (entity) {
return {
label1: entity[field1],
label2: entity[field2],
uniquieId: entity[uniquieId],
concurrencyId: entity.concurrencyId,
innerState: {
data: entity[childEntityName]?.map((innerData) =>
helper(
innerData,
"InventoryLevel3Name",
"InventoryLevel3Information",
"InventoryLevel3Id",
"InventoryLevel4s"
)
),
},
};
}
};