0

For some strange reason, when this data:

// data
visitorsTemplate: [{
  text: '',
  type: 'buttons',
  children: [{
    name: 'email',
    method: (e) => { this.sendEmail(e) }
  }]
}]

Is cloned:

// watch
console.log(this.visitorsTemplate)
const visitorItem = clone(this.visitorsTemplate)
console.log(visitorItem)

With this function:

// utils
export const clone = (...args) => {
  return JSON.parse(JSON.stringify.apply(null, args))
}

the method attribute disappears. Here are the console.logs:

[{
  text: "",
  type: "buttons",
  children": [{
    name: "email",
    method: f method(e)
  }, {
    name: "delete",
    method: f method(e)
  }]
}]

[{
  text: "",
  type: "buttons",
  children": [{
    name: "email"
  }, {
    name: "delete"
  }]
}]

Update: I found out JSON.stringify is removing the methods but I need to create a new array. So how to avoid removing the methods?

alex
  • 7,111
  • 15
  • 50
  • 77

4 Answers4

2

You can implement your own deep clone implmentaion of object. Try this code.

    function deepcloneObject(obj) {
    var clone = {};
    for(var i in obj) {
        if(obj[i] != null &&  typeof(obj[i])=="object")
            clone[i] = deepcloneObject(obj[i]);
        else
            clone[i] = obj[i];
    }
    return clone;
}
Chinmoy Samanta
  • 1,376
  • 7
  • 17
1

the moment you do JSON.stringify, they will try to create a string of your JSON object. when you have method inside, it will try to convert to string also.

So, if you want to have a new instance of object you can use this: http://underscorejs.org/#clone

newObject = _.clone(visitor)

or if you want to be able to create programatically later, you prepare these:

function Visitor(){
    return {
    text: '',
    type: 'buttons',
    children: [Child()]
   }
}

function Child(){
    return  {
       name: 'email',
       method: (e) => { this.sendEmail(e) }
   }
}
Hans Yulian
  • 1,080
  • 8
  • 26
1

Use Object.assign along with Array.prototype.map

const clonedArray = array.map(a => Object.assign({}, a));
DesTroy
  • 390
  • 4
  • 17
1

If you check the JSON Specs here , you will notice that there is no specification for a JSON to contain methods and it contains only data. When you do stringify and then parse, you are taking intermediate step as JSON which is causing this.

For a more detailed account on cloning array of objects, please refer this post.

Hope this helps!

Abhi
  • 1,624
  • 2
  • 16
  • 29