Mahi
Mahi

Reputation: 1727

Can i use for loop here instead of writing hundred lines of code.

This is my function. now its suck when there is 200 id.i don't want to write till 200 id's. can i use for loop here ? like this

for(i=0;i<200;i++){
  "areas": [ {"id": i}]
}

this is my function

var continentsDataProvider = {
 "map": "continentsLow",

"areas": [ {
  "id": 1,
}, {
  "id": "2",
}, {
 }, {
  "id": "3",
}, {
 }, {
  "id": "4",
}, {
 }, {
  "id": "5",
}, {
  } ]

};

Upvotes: 1

Views: 68

Answers (2)

Ori Drori
Ori Drori

Reputation: 192467

You can use a for loop to create the objects or you can use (the much nicer) Array.from:

var continentsDataProvider = {
  "map": "continentsLow",

  "areas": Array.from({ length: 200 }, function(k, v) { return { id: v + 1}; })
};

console.log(continentsDataProvider);

As noted by Emil S. Jørgensen in the comments - Array.from is not supported by internet explorer so you'll need to polyfill it (polyfill code).

Upvotes: 2

gurvinder372
gurvinder372

Reputation: 68423

Yes you can, simply try

If your object is

var continentsDataProvider = {
  "map": "continentsLow",
  "areas": []
};

Run your for-loop as

for(var i=1;i<=200;i++){
  continentsDataProvider.areas.push( {"id": i});
}

Upvotes: 5

Related Questions