I have an array
[{"Name": "MyName","First Name": "ABS","Last Name": "ACS","College": [{"card": {"Name": "card1","Id": "id1"},"Status": "Active","Type": "add","Class": {"Class No": "123"},"Room": {"RoomA": "NULL","RoomB Number": "NULL"}},{"card": {"Name": "card1","Id": "id1"},"Status": "Active","Type": "add","Class": {"Class No": "123"},"Room": {"roomA": "NULL","RoomB Number": "NULL"}}],"Odd Structuring": null,"Accountable Class": "5663"}]
Since I need to flat this array, I have written the below logic
const uniqueKeys = Object.keys(
arr.reduce((result, obj) => Object.assign(result, obj), {})
);
if (uniqueKeys.includes('College')) {
arr.map((item) => {
item.College.map((element, k) => {
let getKeys = Object.entries(element);
getKeys.forEach((data) => {
if (typeof data[1] === 'object') {
let keys = Object.keys(data[1]);
keys.forEach((key) => {
item[`${data[0]} - ${key} ${k + 1}`] = data[1][key];
});
} else {
item[`College - ${data[0]} ${k + 1}`] = data[1];
}
});
});
});
arr = arr.map(({ College, ...data }) => ({ ...data }));
console.log(arr);
}
I am getting the result like this
[{"Accountable Class": "5663","Class - Class No 1": "123","Class - Class No 2": "123","College - Status 1": "Active","College - Status 2": "Active","College - Type 1": "add","College - Type 2": "add","First Name": "ABS","Last Name": "ACS","Name": "MyName","Odd Structuring": null,"Room - RoomA 1": "NULL","Room - RoomB Number 1": "NULL","Room - RoomB Number 2": "NULL","Room - roomA 2": "NULL","card - Id 1": "id1","card - Id 2": "id1","card - Name 1": "card1","card - Name 2": "card1"}]
But my expected result order should be
{"Name" : "MyName","First Name": "ABS","Last Name": "ACS","card Name 1": "card1","card Id 1": "id1","College Status 1": "Active","College Type 1": "add","Class Class No 1": "123","Room RoomA 1": "NULL","Room RoomB Number 1": "NULL","card Name 2": "card1","card Id 2": "id1","College Status 2": "Active","College Type 2": "add","Class Class No 2": "123","Room RoomA 2": "NULL","Room RoomB Number 2": "NULL","Odd Structuring":null,"Accountable Class": '5663'}
Can anyone please help me to get the expected result