I'm trying to get "city" value (in case: Porto, Lisboa, Leiria, Londres) of localstorage and put It in a variable. I wish to do this in a loop for and use each city name in a function.
Now, I'm here:
Object.entries(localStorage).map(([id, valueJSON]) => {
cityName = JSON.parse(JSON.stringify(localStorage.getItem('persist:root', 'allWeather', 'city')));
console.log(cityName)
My return is this:
{"allWeather":"[{"id":0.47266066302275545,"city":"Porto"},{"id":0.8669553925029849,"city":"Lisboa"},{"id":0.5502373167192611,"city":"Leiria"},{"id":0.19655712000371484,"city":"Londres"}]","_persist":"{"version":-1,"rehydrated":true}"}
How can I do this? I appreciate any help.
Try this:
const cities =
// Parse the localstorage item to object
JSON.parse(localStorage.getItem('persist:root', 'allWeather', 'city'))
// Get the allWeather property
.allWeather
// Get the city properties only
.map(weather => weather.city);
You need to convert the object string to JSON using JSON.parse
[{ city }] this part is not right. Change it to city