Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through dictionaries in javascript and access values? [duplicate]

Tags:

javascript

I am not a javascript expert, so I am sure what I am trying to do is pretty straight forward, but, here it is:

I have an array that comes down from a database, it looks like this:

[{"name":"aName","lastName":"aLastname"},{"name":"bName","lastName":"bLastname"}]

I want to iterate through all dictionaries found in the array and access the aName, aLastname etc... so all possible values found in each dictionary, a dictionary at the time.

I tried using eval(), I tried to use JSON.parse, but JSON.parse I think was complaining because I think the object was already coming down as JSON.

How can I do that in javascript?

Thanks

So then I tried to do what was suggested by the "duplicate" answer comment... I did this:

        for(var i=0; i<array.length; i++) {
            var obj = array[i];
            for(var key in obj) {
                var value = obj[key];
                console.log(key+" = "+value);
            }
        }

Problem is that the log is out of order. I get this:

name = aName
name = bName
lastName = aLastName
lastName = bLastName

I want to be sure I iterate through the properties and values in order one dictionary at the time.

What am missing here?

like image 666
zumzum Avatar asked May 23 '26 09:05

zumzum


1 Answers

var test = [{"name":"aName","lastName":"aLastname"},{"name":"bName","lastName":"bLastname"}];

for (var i = 0; i < test.length; ++i) {
    alert(test[i].name + ", " + test[i].lastName);
}

http://jsfiddle.net/1odgpfg4/1/

like image 121
Cody Stott Avatar answered May 24 '26 23:05

Cody Stott