Nodejs: how to clone an object

后端 未结 12 2054
情书的邮戳
情书的邮戳 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条回答
  •  Happy的楠姐
    2020-12-04 19:21

    For a shallow copy, I like to use the reduce pattern (usually in a module or such), like so:

    var newObject = Object.keys(original).reduce(function (obj, item) {
        obj[item] = original[item];
        return obj;
    },{});
    

    Here's a jsperf for a couple of the options: http://jsperf.com/shallow-copying

提交回复
热议问题