A list of cities and their countries is given, stored in the following structure:
let data = [
{
country: 'Poland',
city: 'Cracow',
},
{
country: 'France',
city: 'Paris',
},
{
country: 'Poland',
city: 'Warsaw',
},
{
country: 'Poland',
city: 'Wroclaw',
},
{
country: 'USA',
city: 'New-York',
},
{
country: 'France',
city: 'Nice',
},
{
country: 'USA',
city: 'Boston',
},
]
Write a code that transforms the data structure into this one using loops:
{
'Poland': ['Cracow', 'Warsaw', 'Wroclaw',],
'France': ['Paris', 'Nice'],
'USA': ['Boston', 'New-York' ],
}
My attempt:
obj={};
arr=[];
for ( elem of data){
arr.push(elem.city)
obj[elem.country]=arr
}
console.log(obj)
I have assigned arr to element. How can correct the code to assign only appropriate cities to one country? As a result I have:
{ Poland:
[ 'Cracow',
'Paris',
'Warsaw',
'Wroclaw',
'New-York',
'Nice',
'Boston' ],
France:
[ 'Cracow',
'Paris',
'Warsaw',
'Wroclaw',
'New-York',
'Nice',
'Boston' ],
USA:
[ 'Cracow',
'Paris',
'Warsaw',
'Wroclaw',
'New-York',
'Nice',
'Boston' ] }
How can correct the code to assign only appropriate cities to one country?