Skip to content

Instantly share code, notes, and snippets.

@StormyCube
Created June 25, 2020 16:10
Show Gist options
  • Select an option

  • Save StormyCube/c91dced4fd09f8d65cd2e353d9dbdfbc to your computer and use it in GitHub Desktop.

Select an option

Save StormyCube/c91dced4fd09f8d65cd2e353d9dbdfbc to your computer and use it in GitHub Desktop.
Removes property from root object and all nested objects, recursively
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
namespace YourProject.Extensions
{
public static class JObjectExtensions
{
/// <summary>
/// Removes Recursively all keys named as the property argument
/// </summary>
/// <param name="obj">object to search for property, search is recursive</param>
/// <param name="property">property to remove from the whole object</param>
/// <returns></returns>
public static JObject RemovePropertyRecursive(this JObject obj, string property)
{
obj.Remove(property);
foreach (KeyValuePair<string, JToken> prop in obj)
{
if (prop.Value is JObject)
RemovePropertyRecursive((JObject)prop.Value, property);
if (prop.Value is JArray)
{
JArray array = (JArray)prop.Value;
foreach (JToken item in array.Children())
if (item is JObject)
RemovePropertyRecursive((JObject)item, property);
}
}
return obj;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment