I have a JSON array of objects out of which I need to create an Object of countries and continents like below:
For ex-
{
"Asia":['India','China'],
"Europe": ['Germany','United Kingdom']
}
So basically in above object continents would be a key and all the countries corresponding to that continent would come into array as a value.
This is what I want-
Unite Kingdom
should replace withUK
inside an object.
Below is my code but its giving a wrong output:
const arr = [
{
'id':1,
'geography':'region',
'zone':'Europe',
'countries':['United Kingdom','France','Germany']
},
{
'id':1,
'geography':'global',
'zone':'global',
},
{
'id':1,
'geography':'region',
'zone':'Europe',
'countries':['France','Germany','Netherlands']
}
];
const obj = {};
for(let i=0; i<arr.length; i++) {
//Check if geography is region only
if(arr[i].geography === 'region') {
//Checking if property is already exists in object
if(obj[arr[i].zone]) {
obj[arr[i].countries].map((items) => {
obj[arr[i].zone].push(items);
});
}
//If property is not there then insert
else{
obj[arr[i].zone] = obj[arr[i].countries];
}
}
}
console.log(obj);
Its giving me below output:
{ Europe: undefined }
Someone let me know what I am doing wrong in above code.