使用 JavaScript 从对象中递归删除属性和值的最快方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31728988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using JavaScript what's the quickest way to recursively remove properties and values from an object?
提问by Leon Revill
I need to find the fastest way to remove all $meta
properties and their values from an object, for example:
我需要找到$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
}
}
Should become the following given that the $meta
property could be at any point in the object so some form of recursion will probably be needed.
考虑到该$meta
属性可能位于对象中的任何一点,因此可能需要某种形式的递归,因此应该成为以下内容。
{
"part_one": {
"name": "My Name",
"something": "123"
},
"part_two": [
{
"name": "name",
"dob": "dob"
},
{
"name": "name",
"dob": "dob"
}
]
}
Any help or advice would be greatly appreciated!
任何帮助或建议将不胜感激!
Thank you!
谢谢!
回答by Joseph Marikle
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);
回答by Rene Wooller
As @floor commented above:
正如@floor 上面评论的那样:
JSON.parse(JSON.stringify(obj, (k,v) => (k === '$meta')? undefined : v))
JSON.parse(JSON.stringify(obj, (k,v) => (k === '$meta')? undefined : v))
回答by Kyle
// 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>';
回答by dpmott
(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.
仅供参考,typeof null === 'object',因此在@joseph-marikle 提供的removeMeta() 示例中,该函数将在空值上递归。
Read more here: why is typeof null "object"?
在此处阅读更多信息:为什么 typeof 为 null “对象”?
回答by Nico
Here is a function that takes either a string or an array of strings to remove recursively (based on Joseph's answer):
这是一个函数,它接受一个字符串或一个字符串数组来递归删除(基于 Joseph 的回答):
// 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
}
回答by Alex Montoya
I created this functions when any keyis in any levelin the object using the reference function of @Joseph Marikle
当任何键位于对象中的任何级别时,我使用@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"));
回答by Jonathan
// 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');