How to create and clone a JSON object?

后端 未结 8 685
独厮守ぢ
独厮守ぢ 2020-12-13 18:04

I was wondering how can I create a JSON (JS) object and then clone it.

相关标签:
8条回答
  • 2020-12-13 18:42

    Just do

    var x = {} //some json object here
    var y = JSON.parse(JSON.stringify(x)); //new json object here
    
    0 讨论(0)
  • 2020-12-13 18:42

    This is an issue I have often met when parsing JSON and reusing it several times in the code. And you want to avoid re-parsing every time from the original JSON string, or going the serialize/parse way which is the less efficient way.

    So in these cases where you want to adjust the parsed object but still keep the original unchanged, use the following function in both server (NodeJs) or client javascript code. The jQuery clone function is less efficient because they treat the cases for functions, regexp, etc. The function below, only treats the JSON supported types (null, undefined, number, string, array and object):

    function cloneJSON(obj) {
        // basic type deep copy
        if (obj === null || obj === undefined || typeof obj !== 'object')  {
            return obj
        }
        // array deep copy
        if (obj instanceof Array) {
            var cloneA = [];
            for (var i = 0; i < obj.length; ++i) {
                cloneA[i] = cloneJSON(obj[i]);
            }              
            return cloneA;
        }                  
        // object deep copy
        var cloneO = {};   
        for (var i in obj) {
            cloneO[i] = cloneJSON(obj[i]);
        }                  
        return cloneO;
    }
    
    0 讨论(0)
提交回复
热议问题