Aldren Terante
Aldren Terante

Reputation: 189

How can I insert the data inside a new object in for loop?

Is this possible? When I try to do this the output is not what I expected. Heres is

var data = 10,
    test = new Array;

for (var i = 0; i < data; i++) {
  test = {
       i : {
        'Title' : 'Title-Data',
        'optionFilter' : {
          'AssetClass' : 'AssetClass-Data',
          'Region' : 'Region-Data',
          'Style' : 'Style-Data',
          'TypeofClient' : 'TypeofClient-Data'
        }
      },
  }
};

console.log( test );

Thanks, :)

Upvotes: 2

Views: 92

Answers (2)

Sarath
Sarath

Reputation: 9156

better to use new Array() or just vat test = []; to declare an array then use push method to populate an array

    var data = 10,
        test = new Array();

    for (var i = 0; i < data; i++) {
      test.push({           
            'Title' : 'Title-Data',
            'optionFilter' : {
                 'AssetClass' : 'AssetClass-Data',
                 'Region' : 'Region-Data',
                 'Style' : 'Style-Data',
                 'TypeofClient' : 'TypeofClient-Data' 
             }          
          });
   }

Upvotes: 2

p.s.w.g
p.s.w.g

Reputation: 149030

Since test is an array, just use the push method.

for (var i = 0; i < data; i++) {
  test.push({
        'Title' : 'Title-Data',
        'optionFilter' : {
          'AssetClass' : 'AssetClass-Data',
          'Region' : 'Region-Data',
          'Style' : 'Style-Data',
          'TypeofClient' : 'TypeofClient-Data'
        }
      });
}

If you wanted to achieve something similar with an object, it would look a bit like this:

var data = 10,
    test = {};

for (var i = 0; i < data; i++) {
  test[i] = {
        'Title' : 'Title-Data',
        'optionFilter' : {
          'AssetClass' : 'AssetClass-Data',
          'Region' : 'Region-Data',
          'Style' : 'Style-Data',
          'TypeofClient' : 'TypeofClient-Data'
        }
      };
}

Upvotes: 5

Related Questions