How can I clone an object and iterate over one of its properties?

I am trying to clone an object as part of a promise and iterate over its property.

It seems that you are working, you get an array of objects where it page_numincreases 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 each time creates an object from scratch.

When I try to clone an existing object like this, 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)

It does not seem to work, the options object seems to iterate over the last created object { body: { action: 'read', page_num: 44, page_size: 5 } }for each iteration.

How can I clone an object and iterate over one of its properties?

+4
source share
1 answer

Yes, you're right, the underline function is clone not deep .

, new, .

clone (). :

. , .


, , , Underscore . cloneDeep, , :)

+1
source

All Articles