Home > Net >  Delete all JSON keys nested having specific name
Delete all JSON keys nested having specific name

Time:12-17

I want to delete all occurances of keynames like etag,formattedType and metadata in the object using dynamic iteration of whole object

 var myjson   {
        "etag": "%EiIBAgMFBgcICQoLDA0ODxATFBUWGSEiIyQlJicuNTc9Pj9AGgECIdgxQTUREdTBneFMzZz0=",
        "names": [{
            "unstructuredName": "Natalie Victor",
            "displayNameLastFirst": "Victor, Natalie",
            "familyName": "Victor",
            "displayName": "Natalie Victor",
            "givenName": "Natalie",
            "metadata": {
                "source": {
                    "id": "c8de0718a7c3458",
                    "type": "CONTACT"
                },
                "primary": true
            }
        }],
        "photos": [{
            "metadata": {
                "primary": true,
                "source": {
                    "id": "c8de0718a7c3458",
                    "type": "CONTACT"
                }
            },
            "url": "https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAdAA/V8BNOaftJmdYPfvspCwKr2nuTmSEuXTHowCLcDEAEiGQoBThD___________8BGKjbxPr______wE/s100/photo.jpg",
            "default": true
        }],
        "memberships": [{
            "metadata": {
                "source": {
                    "type": "CONTACT",
                    "id": "c8de0718a7c3458"
                }
            },
            "contactGroupMembership": {
                "contactGroupId": "6a68e3a408126601",
                "contactGroupResourceName": "contactGroups/6a68e3a408126601"
            }
        }, {
            "contactGroupMembership": {
                "contactGroupId": "myContacts",
                "contactGroupResourceName": "contactGroups/myContacts"
            },
            "metadata": {
                "source": {
                    "id": "c8de0718a7c3458",
                    "type": "CONTACT"
                }
            }
        }],
        "phoneNumbers": [{
            "value": "6767674765",
            "formattedType": "Home",
            "canonicalForm": " 916767674765",
            "metadata": {
                "primary": true,
                "source": {
                    "id": "c8de0718a7c3458",
                    "type": "CONTACT"
                }
            },
            "type": "home"
        }],
        "emailAddresses": [{
            "type": "home",
            "formattedType": "Home",
            "value": "[email protected]",
            "metadata": {
                "source": {
                    "id": "c8de0718a7c3458",
                    "type": "CONTACT"
                },
                "primary": true
            }
        }],
        "biographies": [{
            "contentType": "TEXT_PLAIN",
            "value": "Email: [email protected]\nName.Last: Victor\nName.First: Natalie\nPhone: 6767674765",
            "metadata": {
                "primary": true,
                "source": {
                    "id": "c8de0718a7c3458",
                    "type": "CONTACT"
                }
            }
        }],
        "resourceName": "people/c904625878430659672"
    }

I only know to use delete key by names such as

delete myjson.etag
delete myjson.names[0].metadata

How do I iterate the complete json since some of the json has arrays and nested structures which are not known in advance.

Hence a remove_keys(myjson, ["etag","memberships","formattedType","metadata"]) should render a result

var myjson   {
        "names": [{
            "unstructuredName": "Natalie Victor",
            "displayNameLastFirst": "Victor, Natalie",
            "familyName": "Victor",
            "displayName": "Natalie Victor",
            "givenName": "Natalie",
        }],
        "photos": [{
            "url": "https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAdAA/V8BNOaftJmdYPfvspCwKr2nuTmSEuXTHowCLcDEAEiGQoBThD___________8BGKjbxPr______wE/s100/photo.jpg",
            "default": true
        }],
        "phoneNumbers": [{
            "value": "6767674765",
            "canonicalForm": " 916767674765",
            "type": "home"
        }],
        "emailAddresses": [{
            "type": "home",
            "value": "[email protected]",
        }],
        "biographies": [{
            "contentType": "TEXT_PLAIN",
            "value": "Email: [email protected]\nName.Last: Victor\nName.First: Natalie\nPhone: 6767674765",
        }],
        "resourceName": "people/c904625878430659672"
    }

CodePudding user response:

You need a recursive function for this task:

function filter(obj: any, list: string[]) {
  if (obj && typeof obj === 'object') {
    for (let item in obj) {
      if (list.includes(item)) {
        delete obj[item];
      } else {
        if (Array.isArray(obj[item])) {
          for (let el of obj[item]) {
            filter(el, list);
          }
        } else {
          filter(obj[item], list);
        }
      }

    }
  }
  return obj;
}

// example usage: 
let a = {b: 5, c: 6, d: { a: 1, b: 2}}
filter(a, ['b']);
console.log(a);

CodePudding user response:

this recursive function will solve your problem

var myjson = {
   "etag":"%EiIBAgMFBgcICQoLDA0ODxATFBUWGSEiIyQlJicuNTc9Pj9AGgECIdgxQTUREdTBneFMzZz0=",
   "names":[
      {
         "unstructuredName":"Natalie Victor",
         "displayNameLastFirst":"Victor, Natalie",
         "familyName":"Victor",
         "displayName":"Natalie Victor",
         "givenName":"Natalie",
         "metadata":{
            "source":{
               "id":"c8de0718a7c3458",
               "type":"CONTACT"
            },
            "primary":true
         }
      }
   ],
   "photos":[
      {
         "metadata":{
            "primary":true,
            "source":{
               "id":"c8de0718a7c3458",
               "type":"CONTACT"
            }
         },
         "url":"https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAdAA/V8BNOaftJmdYPfvspCwKr2nuTmSEuXTHowCLcDEAEiGQoBThD___________8BGKjbxPr______wE/s100/photo.jpg",
         "default":true
      }
   ],
   "memberships":[
      {
         "metadata":{
            "source":{
               "type":"CONTACT",
               "id":"c8de0718a7c3458"
            }
         },
         "contactGroupMembership":{
            "contactGroupId":"6a68e3a408126601",
            "contactGroupResourceName":"contactGroups/6a68e3a408126601"
         }
      },
      {
         "contactGroupMembership":{
            "contactGroupId":"myContacts",
            "contactGroupResourceName":"contactGroups/myContacts"
         },
         "metadata":{
            "source":{
               "id":"c8de0718a7c3458",
               "type":"CONTACT"
            }
         }
      }
   ],
   "phoneNumbers":[
      {
         "value":"6767674765",
         "formattedType":"Home",
         "canonicalForm":" 916767674765",
         "metadata":{
            "primary":true,
            "source":{
               "id":"c8de0718a7c3458",
               "type":"CONTACT"
            }
         },
         "type":"home"
      }
   ],
   "emailAddresses":[
      {
         "type":"home",
         "formattedType":"Home",
         "value":"[email protected]",
         "metadata":{
            "source":{
               "id":"c8de0718a7c3458",
               "type":"CONTACT"
            },
            "primary":true
         }
      }
   ],
   "biographies":[
      {
         "contentType":"TEXT_PLAIN",
         "value":"Email: [email protected]\nName.Last: Victor\nName.First: Natalie\nPhone: 6767674765",
         "metadata":{
            "primary":true,
            "source":{
               "id":"c8de0718a7c3458",
               "type":"CONTACT"
            }
         }
      }
   ],
   "resourceName":"people/c904625878430659672"
}
function removeKeys(obj,keys){
    if(Array.isArray(obj)){
      obj.forEach(innerObj=>{
      removeKeys(innerObj,keys)
      })
    }else{
      keys.forEach(k=>{
      delete obj[k];
      })
      Object.keys(obj).forEach(key=>{
       if(typeof obj[key]=='object'){
       removeKeys(obj[key],keys)
       }
      })
    }
 }
 
 removeKeys(myjson, ["etag","memberships","formattedType","metadata"])
 console.log(myjson);

CodePudding user response:

Conversely, it may be faster in some interpreters to rebuild the object, rather than delete keys.

function removeKeys(obj, keys) {
    if (Array.isArray(obj))
        return obj.map(v => removeKeys(v, keys))
    else if (typeof obj == "object" && obj != null) {
        const _obj = {}
        Object.keys(obj).forEach(k => {
            if(!keys.includes(k)) _obj[k] = removeKeys(obj[k], keys)
        })
        return _obj
    }
    else
        return obj
}


console.log(removeKeys(myjson, ["etag","memberships","formattedType","metadata"]))
  • Related