Using JavaScript what's the quickest way to recursively remove properties and values from an object?

前端 未结 7 947
攒了一身酷
攒了一身酷 2020-12-03 21:03

I need to find the fastest way to remove all $meta properties and their values from an object, for example:

{
  \"part_one\": {
    \"name\": \"         


        
7条回答
  •  爱一瞬间的悲伤
    2020-12-03 21:38

    Here is a function that takes either a string or an array of strings to remove recursively (based on Joseph's answer):

    // removes all propsToRemove (passed as an array or string), drilling down up to maxLevel times
    // will modify the input and return it
    du.removeAllPropsFromObj = function(obj, propsToRemove, maxLevel) {
        if (typeof maxLevel !== "number") maxLevel = 10
        for (var prop in obj) {
            if (typeof propsToRemove === "string" && prop === propsToRemove)
                delete obj[prop];
            else if (propsToRemove.indexOf(prop) >= 0)      // it must be an array
                delete obj[prop];
            else if (typeof obj[prop] === "object" && maxLevel>0)
                du.removeAllPropsFromObj(obj[prop], propsToRemove, maxLevel-1);
        }
        return obj
    }
    

提交回复
热议问题