0

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?

4
  • Hello Manwal, i am pretty much a newbie to javascript programming. I have just started learning. So didnt try much as i was not sure what to do. Commented Jan 16, 2015 at 10:11
  • nit-pick: you don't have an array, you have a JSON string, that -when parsed- will yield an object. An object is not the same as an array Commented Jan 16, 2015 at 10:12
  • Thanks a lot for all your answers in a very short time. I am very much grateful. I tried the code by "Pavel" and "belhyk" and it is giving me the results as expected. Just one question. In future the json string grows a lot and contains so much of data, any of these answers given below should work, isnt it? Commented Jan 16, 2015 at 10:44
  • All answers will work. But if your json will grow, I suggest to look at performance (see my answer bellow). Good luck Commented Jan 16, 2015 at 11:17

4 Answers 4

1

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for all your answers in a very short time. I am very much grateful. I tried the code and it is giving me the results as expected. Just one question. In future the json string grows a lot and contains so much of data, any of these answers given below should work, isnt it?
1
function getStateByCityName (cityName) {
    var states = {};
    try {
        states = JSON.parse(sessionStorage.getitem('states'));
    } catch (e) {
    }
    for (var state in states) {
        for (var i = 0; i < states[state].length; i ++) {
            if (states[state][i] == cityName)
                return state;
        }
    }
    return null;
}

6 Comments

How can you iterate over a string?
You must do a JSON.parse
I have added parsing of a string
Adding a try...catch without really handling the error doesn't really do much good in my opinion. You just really "hide" the error, which means you cannot differentiate between when the states data could not be read for some reason and when you asked for a cityName not present.
try...catch for "JSON.parse" is a minimal handling for this function
|
1

Or simply use if (states[state].indexOf(cityName) !== -1)

getStateByCityName(cityName) {
    var statesRaw = sessionStorage.getitem('states');
    var states = JSON.parse(statesRaw);
    for (var state in states) {
        if (states[state].indexOf(cityName) !== -1) {
            return state;
        }
    }
    return false;
}

Or in EcmaScript 5 loop style :))

getStateByCityName(cityName) {
    var statesRaw = sessionStorage.getitem('states');
    var states = JSON.parse(statesRaw);

    Object.keys(states).forEach(function(state) {
        if (states[state].indexOf(cityName) !== -1) {
            return state;
        }
    })
    return false;
}

There are many ways (see other answers too) so let's take a look at performance.

First to iterate through your object http://jsperf.com/object-keys-vs-for-in-with-closure/3

In my browser fastest case was Object.keys for loop, so

getStateByCityName(cityName) {
    var statesRaw = sessionStorage.getitem('states');
    var states = JSON.parse(statesRaw);
    var states_keys = Object.keys(states);

    for (var i = 0, l = states_keys.length; i < l; i++) {
          // check if city exists
    }
    return false;
}

Next we need to check if city exists in that state. I see two ways to do it: 1) as others suggested iterate with for loop 2) mine suggested .indexOf()

http://jsperf.com/js-for-loop-vs-array-indexof/2 in my browser indexOf() got better results, so final function

getStateByCityName(cityName) {
    var statesRaw = sessionStorage.getitem('states');
    var states = JSON.parse(statesRaw);
    var states_keys = Object.keys(states);

    for (var i = 0, l = states_keys.length; i < l; i++) {
        if (states[states_keys[i]].indexOf(cityName) !== -1) {
            return states_keys[i];
        }
    }
    return false;
}

And as some one suggested use try/catch

getStateByCityName(cityName) {
    var states = {};
    try {
        states = JSON.parse(sessionStorage.getitem('states'));
    } catch (e) {
    }
    var states_keys = Object.keys(states);

    for (var i = 0, l = states_keys.length; i < l; i++) {
        if (states[states_keys[i]].indexOf(cityName) !== -1) {
            return states_keys[i];
        }
    }
    return false;
}

1 Comment

Thank you Arūnas Smaliukas for giving me this whole bunch of information on this. I will follow these.
0

That should work but can't test it:

function (arrayTarget, itemToSearch){
    for (x in arrayTarget) {
        for(y in arrayTarget[x])
            if(itemToSearch == arrayTarget[x][y])
                 return x;   
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.