0

I have an array which looks like this:

public var meatItems:Array = [{label: "None", data: 0},
                              {label: "Chicken", data: 1},
                              {label:"Beef", data: 2},
                              {label: "Ham", data: 3},
                              {label: "Lamb", data: 4},
                              {label: "Pork", data: 5},
                              {label: "Sausages", data: 6},
                              {label: "Venison", data: 7},
                              {label: "Turkey", data: 8},
                              {label: "Duck", data: 9},
                              {label: "Fish", data: 10}];

I want to loop through each item in this array and insert it into a scrolling list by filling the TextField's .text property with that particular item.

var i:Number;
for (i=0;  i < meatItems.length; i++) {
    itemTextField.text = meatItems[i].toString();
    _item = new Item();
    _item.addChild(_itemTextField);
    _item.y = i * _itemPosition;
}

Very simple I know, but I have been working on this for ages, and have not found any answers

At the minute, when I run it, it only displays one item and it says [object Object] instead of the text

EDIT: I have realised that I need to put _itemTextField.text = meatItems[i].label.toString(); to fix the text issue, but it still only displays one item, what is wrong with my loop?

1 Answer 1

1

meatItems[0] (for example) is {label: "None", data: 0}. That is an object. When converting an object to a string using the toString method, objects are represented as [object Object], regardless of their contents. If you want a more useful output, you need to construct that yourself.

For example:

_itemTextField.text = meatItems[i].label + '(' + meatItems[i].data + ')';

[…] but it still only displays one item, what is wrong with my loop?

The other issue is that you loop through your array, and keep setting the text field’s text property to the current item. That means you overwrite the old value in every iteration and only the last one stays. If you want to have them all inside the text field, you can for example append the new text (here with a separating comma at the end of each item—that means that there will be one trailing comma in the end, which you might want to strip off):

_itemTextField.text += meatItems[i].label +  ', ';
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, I implemented a slightly different fix that I had previous knowledge of that I will post above.

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.