1

I have the following code, with the intention of defining and using a list of objects, but I get an 'undefine' for post_title. What am I doing wrong? I don't want to name the array as a property of an object, I just want a collection/array of objects.

var templates = [{ "ID": "12", "post_title": "Our Title" }
    , { "ID": "14", "post_title": "pwd" }];
function templateOptionList() {
    for(var t in templates) {
        console.log(t.post_title);
    }
}
$(function () {
    templateOptionList();
});
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
ProfK
  • 49,207
  • 121
  • 399
  • 775
  • I hope you don't mind, but I've edited the question title/tags to remove references to JSON (this isn't JSON: JSON is a string representation of object/array data that just looks like object/array literal syntax in JavaScript). – nnnnnn Dec 05 '11 at 04:02

1 Answers1

5

You're defining the array correctly, but that's not how you iterate over an array in JavaScript. Try this:

function templateOptionList() {
    for(var i=0, l=templates.length; i<l; i++) {
        var t=templates[i];
        console.log(t.post_title);
    }
}

A nicer (albeit a little slower) way of doing this that only works in newer browsers would be to use Array.forEach:

function templateOptionList() {
    templates.forEach(function(t) {
        console.log(t.post_title);
    });
}
icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • How much newer must a browser be? I'm targeting the WordPress market here, and who knows how backward their targets are. – ProfK Dec 05 '11 at 03:57
  • @ProfK: Find `Array.prototype.forEach` in [here](http://kangax.github.com/es5-compat-table/). It looks like most current browsers support it except for IE 8 and below. – icktoofay Dec 05 '11 at 04:01
  • [In other words](http://gs.statcounter.com/#browser_version-ww-monthly-201011-201111) a significant percentage of users can't use `Array.prototype.forEach`... – nnnnnn Dec 05 '11 at 04:07
  • You can [shim it](https://github.com/kriskowal/es5-shim) if you want, but it's trivial to iterate without it here. – icktoofay Dec 05 '11 at 04:10
  • 1
    Circling back around, realized this was answered before my post, SO didn't remind me fast enough. Anyways, check out this answer for a quickly on why not use to use `for .. in` on arrays http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays – Ryan Gibbons Dec 05 '11 at 04:35