My goal is to transform an object with objects inside into an array of objects. The initial data looks like this:
"data" :{
"tDetails": {
"tName": "Limited",
"tPay": "xyz"
},
"bDetails": {
"bName": "name",
"bid": "bid",
"bNo": "123456"
},
"iDetails": {
"iName": "iname",
"iBranch": "ibranch"
}
}
The objective is to convert it into an array of objects, iterating over the three headers (tDetails, iDetails, bDetails) as follows:
const newData = [
{
"id": 1,
"title": "tDetails",
"content": [
{
"id": 1,
"key": "tName",
"value": "Limited"
},
{
"id": 2,
"key": "tPay",
"value": "xyz"
}
]
},
{
"id": 2,
"title": "bDetails",
"content": [
{
"id": 1,
"key": "bid",
"value": "12345"
}
]
},
{
"id": 3,
"title": "iDetails",
"content": [
{
"id": 1,
"key": "iName",
"value": "iname"
},{
"id":2,
"key": "iBranch",
"value": "ibranch"
}
]
}
]
const NewData = () => {
let newDetails = [];
let newHeader = '';
for (const header in data) {
// header here is 'tDetails', bDetails, iDetails
const headerData = data[header];
newDetails = Object.entries(headerData).map(([key, value]) => ({
key,
value,
}));
newHeader = header;
}
return [
{
title: newHeader,
content: newDetails,
}
];
};
Currently, only the last part of the data (iDetails) is returned due to the for loop. What changes should be made to fix this issue?