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();
});
1
  • 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). Commented Dec 5, 2011 at 4:02

1 Answer 1

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);
    });
}
Sign up to request clarification or add additional context in comments.

5 Comments

How much newer must a browser be? I'm targeting the WordPress market here, and who knows how backward their targets are.
@ProfK: Find Array.prototype.forEach in here. It looks like most current browsers support it except for IE 8 and below.
In other words a significant percentage of users can't use Array.prototype.forEach...
You can shim it if you want, but it's trivial to iterate without it here.
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 stackoverflow.com/questions/500504/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.