lundi 29 juin 2015

How can I clone an object and iterate over one of it's properties?


I'm trying to clone an object within a promise and iterate a property of it.

This seems to work, you get an array of objest where page_num is incremented from 2 to 44.

var allOptions = _.map(_.range(2, 45), function(page){
  return { body: { action: 'read', page_num: page, page_size: 5 }}
})

Promise.map(allOptions, function(options){
  return Promise.resolve(options).delay(3000)
}).then(console.log)

However this example above is creating an object from scratch every time.

When I try to clone an existing object like so I get the behavior described below.

var masterOptions = { body: { action: 'read', page_num: 1, page_size: 5 }}

var allOptions = _.map(_.range(2, 45), function(page){
  var options = _.clone(masterOptions)
  options.body.page_num = page
  return options
})

Promise.map(allOptions, function(options){
  return Promise.resolve(options).delay(3000)
}).then(console.log)

or

Promise.map(_.range(2, 45), function(page){
  var options = _.clone(masterOptions)
  options.body.page_num = page
  return Promise.resolve(options).delay(3000)
}).then(console.log)

These do not seem to work, the options object seems to be iterating over the last produced object { body: { action: 'read', page_num: 44, page_size: 5 } } for each iteration.

How can I clone an object and iterate over one of it's properties?


Aucun commentaire:

Enregistrer un commentaire