How to Deep clone in javascript

前端 未结 19 1760
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:06

How do you deep clone a JavaScript object?

I know there are various functions based on frameworks like JSON.parse(JSON.stringify(o)) and $.extend(t

19条回答
  •  故里飘歌
    2020-11-22 02:52

    There should be no real world need for such a function anymore. This is mere academic interest.

    As purely an exercise, this is a more functional way of doing it. It's an extension of @tfmontague's answer as I'd suggested adding a guard block there. But seeing as I feel compelled to ES6 and functionalise all the things, here's my pimped version. It complicates the logic as you have to map over the array and reduce over the object, but it avoids any mutations.

    const cloner = (x) => {
        const recurseObj = x => (typeof x === 'object') ? cloner(x) : x
        const cloneObj = (y, k) => {
            y[k] = recurseObj(x[k])
            return y
        }
        // Guard blocks
        // Add extra for Date / RegExp if you want
        if (!x) {
            return x
        }
        if (Array.isArray(x)) {
            return x.map(recurseObj)
        }
        return Object.keys(x).reduce(cloneObj, {})
    }
    const tests = [
        null,
        [],
        {},
        [1,2,3],
        [1,2,3, null],
        [1,2,3, null, {}],
        [new Date('2001-01-01')], // FAIL doesn't work with Date
        {x:'', y: {yx: 'zz', yy: null}, z: [1,2,3,null]},
        {
            obj : new function() {
                this.name = "Object test";
            }
        } // FAIL doesn't handle functions
    ]
    tests.map((x,i) => console.log(i, cloner(x)))

提交回复
热议问题