thejson = [ { name: 'Jany', id: '1246956' },
{ name: 'Azeez', id: '2246306' },
{ name: 'William', id: '22525926' },
]
How do I use a "foreach" loop and print out each name?
thejson = [ { name: 'Jany', id: '1246956' },
{ name: 'Azeez', id: '2246306' },
{ name: 'William', id: '22525926' },
]
How do I use a "foreach" loop and print out each name?
Share Improve this question edited Jul 24, 2016 at 14:49 Farcaller 3,0901 gold badge28 silver badges42 bronze badges asked Apr 27, 2011 at 19:44 TIMEXTIMEX 273k368 gold badges802 silver badges1.1k bronze badges 3- 3 It is not JSON. It is an array of objects. – Felix Kling Commented Apr 27, 2011 at 19:47
- Oh thats right. It's not json haha. I get it, thanks. – TIMEX Commented Apr 27, 2011 at 19:50
- Perhaps reword the title of the question, then? – johnsyweb Commented Apr 28, 2011 at 3:33
2 Answers
Reset to default 5var i;
for (i = 0; i < thejson.length; i++) {
alert(thejson[i].name);
}
thejson.forEach(function (e) { printOut(e.name); });
should do the trick. You'll have to define "printOut" of course.
If you're concerned about older browser patibility, this works:
for (var i = 0, len = thejson.length; i < len; i++) {
printOut(thejson[i].name);
}
Should work on every browser back to the dawn of Javascript.