Cloning an Object in Node.js

后端 未结 21 1910
情书的邮戳
情书的邮戳 2020-11-28 02:03

What is the best way to clone an object in node.js

e.g. I want to avoid the situation where:

var obj1 = {x: 5, y:5};
var obj2 = obj1;
obj2.x = 6;
con         


        
21条回答
  •  遥遥无期
    2020-11-28 02:38

    Simple and the fastest way to clone an Object in NodeJS is to use Object.keys( obj ) method

    var a = {"a": "a11", "b": "avc"};
    var b;
    
    for(var keys = Object.keys(a), l = keys.length; l; --l)
    {
       b[ keys[l-1] ] = a[ keys[l-1] ];
    }
    b.a = 0;
    
    console.log("a: " + JSON.stringify(a)); // LOG: a: {"a":"a11","b":"avc"} 
    console.log("b: " + JSON.stringify(b)); // LOG: b: {"a":0,"b":"avc"}
    

    The method Object.keys requires JavaScript 1.8.5; nodeJS v0.4.11 supports this method

    but of course for nested objects need to implement recursive func


    Other solution is to use native JSON (Implemented in JavaScript 1.7), but it's much slower (~10 times slower) than previous one

    var a = {"a": i, "b": i*i};
    var b = JSON.parse(JSON.stringify(a));
    b.a = 0;
    

提交回复
热议问题