I am trying to convert object with object inside to array of objects. I have the data as:
"data" :{
"tDetails": {
"tName": "Limited",
"tPay": " xyz",
},
"bDetails": {
"bName": "name",
"bid": "bid",
"bNo": "123456",
},
"iDetails": {
"iName": "iname",
"iBranch": "ibranch",
},
}
i want to convert it to array of objects with each iteration over the three headers(tDetails, iDetails,bDetails) as:
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,
},
];
};
This returns me the data of only the last part(iDetails) as it is returned after the for loop.What should be changed here
Map the object's entries instead of using for..in, and in the callback, return the transformed object.
const data={tDetails:{tName:"Limited",tPay:" xyz"},bDetails:{bName:"name",bid:"bid",bNo:"123456"},iDetails:{iName:"iname",iBranch:"ibranch"}};
const newData = Object.entries(data).map(([title, obj], i) => ({
title,
id: i + 1,
content: Object.entries(obj).map(([key, value], j) => ({
id: j + 1,
key,
value
}))
}));
console.log(newData);