简体   繁体   English

如何克隆对象并迭代其中一个属性?

[英]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. 我正在尝试克隆一个promise中的对象并迭代它的属性。

This seems to work, you get an array of objest where page_num is incremented from 2 to 44. 这似乎有效,你得到一个objest数组,其中page_num从2增加到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. 这些似乎不起作用,options对象似乎在每次迭代时迭代最后生成的对象{ body: { action: 'read', page_num: 44, page_size: 5 } }

How can I clone an object and iterate over one of it's properties? 如何克隆对象并迭代其中一个属性?

Yes, you're right, Underscore 's clone function isn't deep . 是的,你是对的, Underscoreclone功能并不

This means that each property of the object you're cloning will be a new variable, but that variable will be populated simply by copying the content of the corresponding original one. 这意味着您要克隆的对象的每个属性都是一个变量,但只需复制相应原始变量的内容即可填充该变量。

That is actually mentioned in the documentation for Underscore 's clone function (link) . 这实际上是在Underscoreclone功能(链接)的文档中提到的。 Here's what is said: 这是说什么:

Create a shallow-copied clone of the provided plain object . 创建提供的普通 对象的浅复制克隆。 Any nested objects or arrays will be copied by reference, not duplicated. 任何嵌套对象或数组都将通过引用复制,而不是重复。


So, as you guessed, it seems that there's no out-of-the-box deep copy function in Underscore right now. 因此,当你猜到了,它似乎有一个在没有下划线外的开箱深拷贝功能现在。 Using cloneDeep as you mentioned in your comment will indeed resolve your issue :) 正如您在评论中提到的那样使用cloneDeep确实可以解决您的问题:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM