使用JavaScript以递归方式从对象中删除属性和值的最快方法是什么?

时间:2015-07-30 16:14:25

标签: javascript object recursion javascript-objects

我需要找到从对象中删除所有$meta属性及其值的最快方法,例如:

{
  "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
  }
}

如果$meta属性可能位于对象中的任何位置,那么应该成为以下内容,因此可能需要某种形式的递归。

{
  "part_one": {
    "name": "My Name",
    "something": "123"
  },
  "part_two": [
    {
      "name": "name",
      "dob": "dob"
    },
    {
      "name": "name",
      "dob": "dob"
    }
  ]
}

非常感谢任何帮助或建议!

谢谢!

8 个答案:

答案 0 :(得分:20)

一个简单的自我调用功能就可以做到。

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);




答案 1 :(得分:14)



// 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>';
&#13;
&#13;
&#13;

答案 2 :(得分:11)

正如@floor上面评论的那样:

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

答案 3 :(得分:1)

(道歉,我还没有足够的声誉点直接评论。)

只是FYI,typeof null ==='object',所以在@joseph-marikle提供的removeMeta()示例中,该函数将递归一个空值。

在此处阅读更多内容:why is typeof null "object"?

答案 4 :(得分:1)

这是一个函数,它需要一个字符串或字符串数​​组来递归删除(基于约瑟夫的答案):

// 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
}

答案 5 :(得分:0)

我使用 @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;
 };

示例:

 const _obj = {
       a: "b", b: "e", c: { a: "a", b: "b", c: "c"},
       d: [ { a: "3" }, { b: ["2", "3"] }]};
 console.log(removeAttrDeep(_obj, "b"));

答案 6 :(得分:0)

// recursively delete a key from anywhere in the object
// will mutate the obj - no need to return it
const deletePropFromObj = (obj, deleteThisKey) => {
  if (Array.isArray(obj)) {
    obj.forEach(element => deletePropFromObj(element, deleteThisKey))
  } else if (typeof obj === 'object') {
    for (const key in obj) {
      const value = obj[key]
      if (key === deleteThisKey) delete obj[key]
      else deletePropFromObj(value, deleteThisKey)
    }
  }
}

deletePropFromObj(obj, '$meta');

答案 7 :(得分:-3)

使用某种形式的delete objectName.$meta可以向您发送正确的方向

How do I remove a property from a JavaScript object?