Reputation: 1069
I have JSON that looks like this
const err = [
{
"Error": Name Not Valid",
"Content": [
{
"Name": "Johnz"
}
]
},
{
"Error": "Data Not Valid",
"Content": [
{
"Investor": "3785388",
"ManagedBy": "Johnz"
},
{
"Investor": "1111111",
"ManagedBy": "Mary"
}
]
}]
How can I set it so it looks like this? I need to move anything that appears in the content array to the main structure where title is.
const err= [
{
"Error": "Name Not Valid",
"Name": "Johnz"
},
{
"Error": "Data Not Valid",
"Investor": "3785388",
"ManagedBy": "Johnz"
},
{
"Error": "Data Not Valid"
"Investor": "1111111",
"ManagedBy": "Mary"
}]
Upvotes: 0
Views: 36
Reputation: 31602
It helps if you define a minimal type for the err variable.
An option then would be:
const err: { Error: string, Content: any[] }[] = [
{
"Error": "Name Not Valid",
"Content": [
{
"Name": "Johnz"
}
]
},
{
"Error": "Data Not Valid",
"Content": [
{
"Investor": "3785388",
"ManagedBy": "Johnz"
},
{
"Investor": "1111111",
"ManagedBy": "Mary"
}
]
}];
const flattenedError = err.map(error => {
const flattened = { error: error.Error };
return error.Content.reduce((acc, curent) => {
Object.keys(curent).forEach((key) => {
acc[key] = curent[key];
});
return acc;
}, flattened);
});
A working example can be found here.
Upvotes: 1