Search code examples
javascriptjsonsessionstorage

Javascript array iteration


I have a JavaScript array in sessionStorage and when I do a sessionStorage.getitem('states'), I am getting like this:

"{
    "TamilNadu": [
        "Chennai", 
        "Trichy", 
        "Madurai"
    ],
    "Andhra": [
        "Hyderabad",
        "Vizhag"
    ],
    "Karnataka": [
        "Bangalore",
        "Mysore",
        "Darwad"
    ],
    "Maharashtra": [
        "Mumbai",
        "Pune"
    ]
}"

Now my requirement is to get the state name from the city name. For example if I pass "Mumbai" to a function as a parameter, that function should read this sessionstorage value and return me "Maharashtra".

Could you please help me how to achieve this?


Solution

  • This code:

    sessionStorage.getitem('states')
    

    returns a string. You must parse it with:

    var obj = JSON.parse(sessionStorage.getitem('states')) 
    

    And next access object attributes with square brackets or a dot:

    for (var attr in obj) {
        if (obj.hasOwnProperty(attr) && obj[attr][0] == 'Mumbai') {
            return attr;
        }
    }
    return null;