Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
76
rated 0 times [  82] [ 6]  / answers: 1 / hits: 17684  / 3 Years ago, tue, october 26, 2021, 12:00:00

I'm building an API and getting the data from my database in the given format.

There won't be repetitions like {country: 'India', count: 2, status: 'Active'},{country: 'India', count: 1, status: 'Active'}


const dataFromDB = [
{country: 'India', count: 2, status: 'Active'}, {country: 'USA', count: 3, status: 'Recovered'},
{country: 'India', count: 2, status: 'Recovered'}, {country: 'Russia', count: 1, status: 'Active'},
{country: 'India', count: 1, status: 'Dead'}, {country: 'Brazil', count: 1, status: 'Active'},
{country: 'Canada', count: 1, status: 'Dead'}, {country: 'USA', count: 1, status: 'Active'}
]

But I want to convert my data into a different format before sending it out.


const formatIWant = {
Brazil: {
active: 1,
dead: 0,
recovered: 0
},
Canada: {
active: 0,
dead: 1,
recovered: 0
},
India: {
active: 2,
dead: 1,
recovered: 2
},
Russia: {
active: 1,
dead: 0,
recovered: 0
},
USA: {
active: 1,
dead: 0,
recovered: 3
}
}

How do I tackle this problem.


More From » arrays

 Answers
42

Just loop thru the array of plain objects and create a new object with different keys using each data. This for example




const reformat = (dataFromDB) => {
const formatted = {};

for (const data of dataFromDB) {
formatted[data.country] = {
recovered: 0,
active: 0,
dead: 0,
...formatted[data.country],
[data.status.toLowerCase()]: data.count,
};
}

return formatted;
};

console.log(
reformat([
{ country: 'India', count: 2, status: 'Active' },
{ country: 'USA', count: 3, status: 'Recovered' },
{ country: 'India', count: 2, status: 'Recovered' },
{ country: 'Russia', count: 1, status: 'Active' },
{ country: 'India', count: 1, status: 'Dead' },
{ country: 'Brazil', count: 1, status: 'Active' },
{ country: 'Canada', count: 1, status: 'Dead' },
{ country: 'USA', count: 1, status: 'Active' },
])
);




[#50139] Tuesday, September 21, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
denver

Total Points: 232
Total Questions: 111
Total Answers: 103

Location: South Korea
Member since Sat, Oct 2, 2021
3 Years ago
;