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

Leon Revill picture Leon Revill · Jul 30, 2015 · Viewed 13.7k times · Source

I need to find the fastest way to remove all $meta properties and their values from an object, for example:

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

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

Answer

Joseph Marikle picture Joseph Marikle · Jul 30, 2015

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