user1716672
user1716672

Reputation: 1073

Looping through key values in object

Im getting an array of objects from localstorage:

saved_selection = window.localStorage.getItem('match_selection');

console.log('saved selection obj is ');
console.log(saved_selection);

The output is:

{"236":"Forward_2","243":"Forward_1"} 

Now I want to loop through and get the key and value. So I do:

for(var index in saved_selection) {
    console.log(index + " -> " + saved_selection[index]); 
}

But I get:

0 -> { 
1 -> " 
2 -> 2 
3 -> 3 

etc, instead of:

236 -> Forward_2
243 -> Forward_1

How do I achieve the desired output?

Upvotes: 2

Views: 205

Answers (3)

The Dark Knight
The Dark Knight

Reputation: 5585

You, my friend are trying to get the index of a complete stringized object. It does not work that way. First you have to parse it and break it down to individual components using JSON.parse().

Look below :

JS:

var saved_selection = JSON.parse('{"236":"Forward_2","243":"Forward_1"}') ;

var saved_selection1 = '{"236":"Forward_2","243":"Forward_1"}' ;

for(var index in saved_selection) {
    console.log(index + " -> " + saved_selection[index]); 
}
for(var index in saved_selection1) {
    console.log(index + " -> " + saved_selection1[index]); 
}

The first for loop returns the desired O/P but the second one does not.

Find the working fiddle here :http://jsfiddle.net/eMVNk/2/

Upvotes: 1

dchhetri
dchhetri

Reputation: 7136

You want to parse out the string returned by the localStorage:

saved_selection = JSON.parse( window.localStorage.getItem('match_selection') );

Upvotes: 2

Ilya
Ilya

Reputation: 29703

This means that {"236":"Forward_2","243":"Forward_1"} is instance of String, not an Object.
for

var v1 = '{"236":"Forward_2","243":"Forward_1"}';

this will not works, but for

var v2 = {"236":"Forward_2","243":"Forward_1"};  

You should convert String to Object with JSON.parse method.

saved_selection = JSON.parse(saved_selection);
for(var index in saved_selection) {
    console.log(index + " -> " + saved_selection[index]); 
}

Upvotes: 1

Related Questions