Polymer Clone Objects

How can we clone an object in Polymer?

Example

this.colorsAsc.push({color: 'red'});
this.colorsDesc = this.colorsAsc.reverse();

this.colorsDesc[0].color = 'blue'; // Both will be blue doing this

I can do this in these many functions. What is the most efficient way to deeply clone an object in JavaScript? but I am wondering if there is a way in Polymer to do this?

Angular does this https://docs.angularjs.org/api/ng/function/angular.copy

+2
source share
3 answers

I had the same question here , where I finally found and sent an answer.

Short version:

newElement = element.cloneNode(true);
for(var i in element.properties) {
        newElement[i] = element[i]
      }
0
source

You can try the following hack:

this.colorsDesc = JSON.parse(JSON.stringify(this.colorsAsc.reverse());
0
source

To clone a utility through Polymer

Full implementation:

  (function(callBackFn) {
      Polymer({

          //Component Name
          is: 'my-cloner',

          properties: {
              //Declare a published property 
              cloneableObject: { //Placeholder for Object to be cloned 
                  reflectToAttribute: true,
                  type: Object,
                  notify: true
              }
          },

          attached: function() {
              //Hide if this component got attached
              this.hidden = true;
          },

          getClone: function(incomingcloneableObject) { //Will be called to get the Clone

              this.cloneableObject = this.cloneableObject || incomingcloneableObject;

              switch (typeof this.cloneableObject) {
                  case "undefined":
                      return null;
                      break;
                  case "object":
                      var localClone = this.cloneNode();
                      return (localClone.cloneableObject);
                      break;
                  case "boolean":
                      return new Boolean(this.cloneableObject).valueOf();
                      //Other possible way 
                      //return(this.cloneableObject ? true : false);
                      break;
                  case "number": //NaN is taken care of 
                      return new Number(this.cloneableObject).valueOf();
                      //Other possible way
                      //return(this.cloneableObject * 1);
                      break;
                  case "string":
                      return new String(this.cloneableObject).valueOf();
                      //Other possible way
                      //return(this.cloneableObject + '');
                      break;
                  default:
                      return null;
              }
          }
      });

      //adding Util into window
      callBackFn();

  })(function() {
      window.cloneUtil = document.createElement('my-cloner');
  });
  //To use this util
  //window.cloneUtil.getClone();
0
source

All Articles