Photoshop: Script - how to clone javascript object?

  • 1
  • Question
  • Updated 2 years ago
  • (Edited)
Example

var tempLayerText = layerText;
If I change something in "tempLayerText" then "layerText" is exactly same, because tempLayerText is only reference to layerText. But I want different content in both variables. What is the best way to clone javascript object in JSX?
Photo of Jaroslav Bereza

Jaroslav Bereza

  • 809 Posts
  • 187 Reply Likes

Posted 2 years ago

  • 1
Photo of Max Johnson

Max Johnson, Champion

  • 488 Posts
  • 235 Reply Likes
For shallow property cloning, try this:


//------------------------------------------------------------------------------

doc = app.activeDocument

firstObject = doc.layers[0].artLayers[0]

secondObject = {}


$.writeln ('========================')

for (var prop in firstObject) {

if (firstObject.hasOwnProperty(prop)) {

$.writeln (prop + ' : ' + firstObject[prop])

secondObject[prop] = firstObject[prop];

}

}

$.writeln ('--------------------')

secondObject.name = 'sdkflsjdkfls'

$.writeln ('Name 1: '+firstObject.name)

$.writeln ('Name 2: '+secondObject.name)

$.writeln ('========================\n\n')


//------------------------------------------------------------------------------


As long as the property is a value and not a reference, you should be good... but it it's a reference to another array or object, it just assigns the reference. Like, if you tried to clone a layer set, the [artLayers] property would still be a direct reference to the original art layers. You'd have to make it recursive to do anything more complex...and I don't know how stable that would be.
(Edited)
Photo of Jaroslav Bereza

Jaroslav Bereza

  • 809 Posts
  • 187 Reply Likes
I need deep clone. And I used Jam framework and this code solved it: 
"var tempLayerText = jamJSON.parse(jamJSON.stringify(layerText));"
Photo of Max Johnson

Max Johnson, Champion

  • 488 Posts
  • 235 Reply Likes
Do you know if this carried over function properties correctly? I saw this solution posted online, but I thought someone said it broke function objects translated this way...
(Edited)
Photo of Jaroslav Bereza

Jaroslav Bereza

  • 809 Posts
  • 187 Reply Likes
I don't have functions in my object. Otherwise it could be maybe problem.