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

前端 未结 7 906
攒了一身酷
攒了一身酷 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 22:00
    // 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');
    
    0 讨论(0)
提交回复
热议问题