[Vuejs]-Why are these methods disappearing when I clone the array?

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

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๐Ÿ‘

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๐Ÿ‘

Use Object.assign along with Array.prototype.map

const clonedArray = array.map(a => Object.assign({}, a));
๐Ÿ‘คDesTroy

Leave a comment