3

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?

Anoop Asok
  • 1,311
  • 1
  • 8
  • 20
zumzum
  • 17,984
  • 26
  • 111
  • 172
  • If the server is responding sensibly, this will just be a regular JavaScript array; iterate over it as you would any other array – Jason Baker Sep 25 '14 at 04:57
  • Ok, I think this could very well be a duplicate then. I will close it if I can. Thank you – zumzum Sep 25 '14 at 04:59

2 Answers2

8
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/

Cody Stott
  • 484
  • 1
  • 7
  • 19
  • this works and it also print things in order... – zumzum Sep 25 '14 at 05:13
  • In all fairness, Johnroe Paulo Cañamaque answered slightly faster than me, *but* [this](http://jsperf.com/for-vs-foreach/37) speaks to the performance of `for` over `forEach` in Javascript. – Cody Stott Sep 25 '14 at 05:18
3

You may want to try this.

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

arr.forEach(function(d){
    console.log(d.name, d.lastName);
});
jpcanamaque
  • 1,049
  • 1
  • 8
  • 14
  • Note that if this is in browser javascript, it will not work in IE8 or below. That's easily fixed with a polyfill though – James Hay Sep 25 '14 at 05:02