Skip to content
Advertisement

Nested object needs to be modified

This is the input json which i am reading and trying to change the structure as per requirement .But unable to do so countries i am able to put inside object but timezone i am unable to read .Can any one help clearly i need to work on objects little harder .

let timezone = {
  countries: {
    Algeria: {
      cities: {
        "Algiers": {
          city: "Algiers",
          timezone: "(UTC+01:00) W. central africa standard time",
          ianaTz: "Africa/Algiers",
        },
      },
    },
    Argentina: {
      cities: {
        "Buenos aires": {
          city: "Buenos aires",
          timezone: "(UTC-03:00) Argentina standard time",
          ianaTz: "America/Argentina/Buenos_Aires",
        },
        "Cordoba": {
          city: "Cordoba",
          timezone: "(UTC-03:00) Argentina standard time",
          ianaTz: "America/Argentina/Cordoba",
        },
        "Tucuman": {
          city: "Tucuman",
          timezone: "(UTC-03:00) Argentina standard time",
          ianaTz: "America/Argentina/Tucuman",
        },
      },
    }
  }
}


function editTimezone(timezone) {
  var arr = [];

  for (var key in timezone.countries) {
    var city = timezone.countries[key].cities;
    for (var cit in city) {
      var timezone = timezone.countries[key].cities.cit.timezone; //undefined
    }
    arr.push({
      "country": key,
      "timezone": [timezone]
    })
  }
  console.log(arr);
}

editTimezone(timezone);

//OUTPUT REQUIRED–

[{
"country":"Algeria"
"timezone": ["((UTC+01:00) W. central africa standard time"]
 },
 {   
  "country":"Argentina"
  "timezone": ["(UTC-03:00) Argentina standard time","(UTC-03:00) Argentina standard 
  time","(UTC-03:00) Argentina standard time"]
 }
]

Not sure what logic i should write for achieving the output.

Advertisement

Answer

Script:

function editTimezone() {
  var countries = timezone.countries;
  var arr = Object.keys(countries).map(country => {
    var cities = countries[country].cities;
    return {
      'country': country,
      'timezone' : Object.keys(cities).map(city => cities[city].timezone)
    }
  });

  console.log(arr);
}

Steps:

  • First, get the countries, then map them to create an array.
  • Next, get the list of cities per country then map it again with their own timezones.
  • Lastly, return both the country name and the timezones as an object altogether to get an array of these objects.

Output:

output

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement