Home > other >  Remove underscore prefixes from all keys
Remove underscore prefixes from all keys

Time:12-09

I have data that looks like the following:

[
   {
      "_sourceAddresses":[
         {
            "_street1":"957 Heathcote Unions",
            "_city":"Matteoside",
            "_state":"Hawaii",
            "_postalCode":"69680",
            "_postalCodePlusFour":"7715",
            "_country":"USA",
            "_type":0,
            "_updatedAt":"1991-03-10T22:34:27.000Z",
            "_createdAt":"1970-07-24T09:34:12.000Z"
         }
      ],
      "_emails":[
         {
            "_address":"[email protected]",
            "_primary":true
         }
      ],
      "_phoneNumbers":[
         {
            "_number":"4612902836",
            "_type":0,
            "_carrier":"AT&T"
         }
      ],
      "_customFields":{
         
      },
      "_active":true,
      "_firstName":"Haven",
      "_lastName":"Runolfsdottir",
      "_gender":"M",
      "_sourceIndividualId":"c1126d05-0e5b-4da1-8535-e1061d4163ee",
      "_sourceCampusId":"ae1e70d5-d8bf-4942-b9ea-3da5765e055f",
      "_primaryContact":true,
      "_salutation":"Mrs.",
      "_suffix":"DDS",
      "_birthDate":"1989-02-16T10:06:25.000Z"
   },
   {
      "_sourceAddresses":[
         {
            "_street1":"5910 Langosh Burgs Apt. 281",
            "_city":"West Katheryn",
            "_state":"Arkansas",
            "_postalCode":"49571",
            "_postalCodePlusFour":null,
            "_country":"USA",
            "_type":0,
            "_updatedAt":"1984-01-09T09:34:02.000Z",
            "_createdAt":"1986-01-13T17:36:41.000Z"
         }
      ],
      "_emails":[
         {
            "_address":"[email protected]",
            "_primary":true
         }
      ],
      "_phoneNumbers":[
         {
            "_number":"0608405498",
            "_type":0,
            "_carrier":"Verizon"
         }
      ],
      "_customFields":{
         
      },
      "_active":true,
      "_firstName":"Andreane",
      "_lastName":"Kerluke",
      "_gender":"F",
      "_sourceIndividualId":"0726bfc2-56af-4e46-90ef-c0a286404334",
      "_sourceCampusId":"86fdb656-7e29-4ace-a1c7-149db81c7f5e",
      "_primaryContact":true,
      "_salutation":"Mrs.",
      "_suffix":null,
      "_birthDate":"1979-11-14T10:07:02.000Z"
   }
]

When it is saved as JSON, I'd like to remove the underscores in the keys. Is there an easy way to do this?

I have tried unsuccessfully to adapt this code to accomplish it: Replace dot to underscore in js object keys names

function removeLeadingUnderscores(obj) {
  _.forOwn(obj, (value, key) => {


    if (_.startsWith("_")) {
      const cleanKey = _.substring(1)
      obj[cleanKey] = value;
      delete obj[key];
    }

    // continue recursively looping through if we have an object or array
    if (_.isObject(value)) {
      return removeLeadingUnderscores(value);
    }
  });
  return obj;
}

CodePudding user response:

Since you're planning to save as JSON already, you can use its naturally recursive nature with its reviver parameter to return objects without the underscores. Map the entries of the object to a new object without the leading _.

const arr=[{_sourceAddresses:[{_street1:"957 Heathcote Unions",_city:"Matteoside",_state:"Hawaii",_postalCode:"69680",_postalCodePlusFour:"7715",_country:"USA",_type:0,_updatedAt:"1991-03-10T22:34:27.000Z",_createdAt:"1970-07-24T09:34:12.000Z"}],_emails:[{_address:"[email protected]",_primary:!0}],_phoneNumbers:[{_number:"4612902836",_type:0,_carrier:"AT&T"}],_customFields:{},_active:!0,_firstName:"Haven",_lastName:"Runolfsdottir",_gender:"M",_sourceIndividualId:"c1126d05-0e5b-4da1-8535-e1061d4163ee",_sourceCampusId:"ae1e70d5-d8bf-4942-b9ea-3da5765e055f",_primaryContact:!0,_salutation:"Mrs.",_suffix:"DDS",_birthDate:"1989-02-16T10:06:25.000Z"},{_sourceAddresses:[{_street1:"5910 Langosh Burgs Apt. 281",_city:"West Katheryn",_state:"Arkansas",_postalCode:"49571",_postalCodePlusFour:null,_country:"USA",_type:0,_updatedAt:"1984-01-09T09:34:02.000Z",_createdAt:"1986-01-13T17:36:41.000Z"}],_emails:[{_address:"[email protected]",_primary:!0}],_phoneNumbers:[{_number:"0608405498",_type:0,_carrier:"Verizon"}],_customFields:{},_active:!0,_firstName:"Andreane",_lastName:"Kerluke",_gender:"F",_sourceIndividualId:"0726bfc2-56af-4e46-90ef-c0a286404334",_sourceCampusId:"86fdb656-7e29-4ace-a1c7-149db81c7f5e",_primaryContact:!0,_salutation:"Mrs.",_suffix:null,_birthDate:"1979-11-14T10:07:02.000Z"}];

const stringified = JSON.stringify(
  arr,
  (_, value) => {
    return value && typeof value === 'object' && !Array.isArray(value)
      ? Object.fromEntries(
          Object.entries(value)
            .map(([key, value]) => [key.slice(1), value])
        )
      : value;
  }
);

console.log(stringified);

If some properties don't start with _, you can change .slice(1) to .replace(/^_/, '').

CodePudding user response:

Here's a simplified version of saving the object with removed underscores through simple recursive logic:

let savedJson: any = [];
renamingArray(obj); // obj is your object

function renamingArray(element: any){
  for(let element of obj)
    if (Object.prototype.toString.call(element) === '[object Array]') {
      renamingArray(element);
    else 
      renamingObject(element);
  }
} 

function renamingObject(obj: any){
  let keys = Object.keys(obj)
  for(let objectKey of keys){
    savedJson.push({ [objectKey.substring(1)]: obj[objectKey] }); 
  }
}

console.log(savedJson)
  • Related