Nodejs: how to clone an object

后端 未结 12 2057
情书的邮戳
情书的邮戳 2020-12-04 18:32

If I clone an array, I use cloneArr = arr.slice()

I want to know how to clone an object in nodejs.

12条回答
  •  借酒劲吻你
    2020-12-04 19:20

    Objects and Arrays in JavaScript use call by reference, if you update copied value it might reflect on the original object. To prevent this you can deep clone the object, to prevent the reference to be passed, using lodash library cloneDeep method run command

    npm install lodash

    const ld = require('lodash')
    const objectToCopy = {name: "john", age: 24}
    const clonedObject = ld.cloneDeep(objectToCopy)
    

提交回复
热议问题