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

前端 未结 7 904
攒了一身酷
攒了一身酷 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

    As @floor commented above:

    JSON.parse(JSON.stringify(obj, (k,v) => (k === '$meta')? undefined : v))

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2020-12-03 21:45

    // Helper function
    function removeProps(obj,keys){
      if(obj instanceof Array){
        obj.forEach(function(item){
          removeProps(item,keys)
        });
      }
      else if(typeof obj === 'object'){
        Object.getOwnPropertyNames(obj).forEach(function(key){
          if(keys.indexOf(key) !== -1)delete obj[key];
          else removeProps(obj[key],keys);
        });
      }
    }
    // The object we want to iterate
    var obj = {
      "part_one": {
        "name": "My Name",
        "something": "123",
        "$meta": {
          "test": "test123"
        }
      },
      "part_two": [
        {
          "name": "name",
          "dob": "dob",
          "$meta": {
            "something": "else",
            "and": "more"
          }
        },
        {
          "name": "name",
          "dob": "dob"
        }
      ],
      "$meta": {
        "one": 1,
        "two": 2
      }
    };
    // Utilize the utility
    removeProps(obj,['$meta']);
    // Show the result
    document.body.innerHTML = '<pre>' + JSON.stringify(obj,null,4) + '</pre>';

    0 讨论(0)
  • 2020-12-03 21:52

    (Apologies, I do not yet have enough reputation points to comment directly.)

    Just FYI, typeof null === 'object', so in the removeMeta() example offered by @joseph-marikle, the function will recurse on a null value.

    Read more here: why is typeof null "object"?

    0 讨论(0)
  • 2020-12-03 21:53

    A simple self-calling function can do it.

    function removeMeta(obj) {
      for(prop in obj) {
        if (prop === '$meta')
          delete obj[prop];
        else if (typeof obj[prop] === 'object')
          removeMeta(obj[prop]);
      }
    }
    

    var myObj = {
      "part_one": {
        "name": "My Name",
        "something": "123",
        "$meta": {
          "test": "test123"
        }
      },
      "part_two": [
        {
          "name": "name",
          "dob": "dob",
          "$meta": {
            "something": "else",
            "and": "more"
          }
        },
        {
          "name": "name",
          "dob": "dob"
        }
      ],
      "$meta": {
        "one": 1,
        "two": 2
      }
    }
    
    function removeMeta(obj) {
      for(prop in obj) {
        if (prop === '$meta')
          delete obj[prop];
        else if (typeof obj[prop] === 'object')
          removeMeta(obj[prop]);
      }
    }
    
    removeMeta(myObj);
    
    console.log(myObj);

    0 讨论(0)
  • 2020-12-03 21:54

    I created this functions when any key is in any level in the object using the reference function of @Joseph Marikle

    const _ = require("lodash");
    const isObject = obj => obj != null && obj.constructor.name === "Object";
    const removeAttrDeep = (obj, key) => {
        for (prop in obj) {
          if (prop === key) delete obj[prop];
          else if (_.isArray(obj[prop])) {
            obj[prop] = obj[prop].filter(k => {
              return !_.isEmpty(removeAttrDeep(k, key));
            });
         } else if (isObject(obj[prop])) removeAttrDeep(obj[prop], key);
        }
        return obj;
     };
    

    EXAMPLE:

     const _obj = {
           a: "b", b: "e", c: { a: "a", b: "b", c: "c"},
           d: [ { a: "3" }, { b: ["2", "3"] }]};
     console.log(removeAttrDeep(_obj, "b"));
    
    0 讨论(0)
提交回复
热议问题