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

前端 未结 7 960
攒了一身酷
攒了一身酷 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: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"));
    

提交回复
热议问题