1

I have an array of javascript objects of type:

    var tags = [
        { id: 0, toString: function() { return 'jQuery'; } },
        { id: 1, toString: function() { return 'Python'; } },
    ];

I have a json containing about 100 objects. How could I create my tags array dynamically. I tried the approach below, but it didn't work.

    var tags = [];
    $.ajax({
        url: baseurl,
        dataType: 'json',
        data: {
            "stime": stime // some variable
            },
        type: "POST",
        success: function(_data){
            if (_data.length>0) {
                for (var i=0; i<_data.length; i++) {
                    var _x = { id: _data[i].id, toString: function() { return ''+_data[i].name; } }
                    tags.push(_x);
                }

1 Answers1

1

You are using i inside the toString function. It means that all objects will access the same item, with i out of bounds.

You could use bind instead.

toString: function(name) { return name; }.bind(this, _data[i].name)

Edit

To clarify, i is part of the success closure. That means that when toString is called, i will be taken from the success closure, then _data, and then _data[i] will be used. It means the functions will share the same i.

Also, _data.ids[i] seems wrong. Shouldn't it be _data[i].id?

BBLN
  • 495
  • 6
  • 19