简体   繁体   English

从所有键中删除下划线前缀

[英]Remove underscore prefixes from all keys

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":"labadie.gwendolyn@gmail.com",
            "_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":"labadie_cristopher@yahoo.com",
            "_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.当它保存为 JSON 时,我想删除键中的下划线。 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我尝试修改此代码以完成它,但未成功: 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;
}

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.由于您已经计划保存为 JSON,因此您可以使用其自然递归性质及其 reviver 参数来返回不带下划线的对象。 Map the entries of the object to a new object without the leading _ . Map 将 object 的条目改为没有前导_的新 object。

 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:"labadie.gwendolyn@gmail.com",_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:"labadie_cristopher@yahoo,com":_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(/^_/, '') .如果某些属性_开头,您可以将.slice(1)更改为.replace(/^_/, '')

Here's a simplified version of saving the object with removed underscores through simple recursive logic:这是通过简单的递归逻辑删除下划线的保存 object 的简化版本:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM