Skip to content
Advertisement

How to recursively process a JSON data and return the processed JSON from a function?

I have below JSON data with nested objects. I want to delete the ‘id’ from this structure and return the changed JSON from the function. I have tried to do it recursively below way but not able to return the changed JSON.

var jsonStr = 
{"_id":"7r0c0342e",
"user":"myuser",
"project":"abcd",
"info":{"DOMAIN":{"Department":{"profile":[{"workex":8,"name":"alex","id":82838},
{"workex":8,"name":"smith","id":84838} ]}}} };


processJSON(jsonStr);

function processJSON(jsondata) {
    for (var i in jsondata) {
        var row = jsondata[i];           
        if(typeof row == "object") {
            processJSON(row);              
        } else if(typeof row == 'number') {
            if(i == 'id') {
                delete jsondata[i];                    
            } else {                
                continue;
            }
        } else {
            continue;
        }              
      }   
}

console.log(jsonStr);

How can I return the rest of the JSON from the processJSON() and hold that in a variable ? Secondly, is this the correct way to do it recursively ?

Thanks.

Advertisement

Answer

var jsonStr =
    {
        "_id": "7r0c0342e",
        "user": "myuser",
        "project": "data_mining",
        "info": {
            "DOMAIN": {
                "Department": {
                    "profile": [{"workex": 8, "name": "alex", "id": 82838},
                        {"workex": 8, "name": "smith", "id": 84838}]
                }
            }
        }
    };
let modifedJson = JSON.parse(JSON.stringify(jsonStr));

parseJson = function (json) {
    for (let key in json) {
        if (key === 'id') {
            delete json[key];
        }
        else if (typeof json[key] === 'object') {
            parseJson(json[key])
        }

    }
}
parseJson(modifedJson)
console.log('modified',modifedJson)
console.log('original',jsonStr)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement