简体   繁体   中英

How to lowercase the first alphabet of a key in an object?

I have a JavaScript object and I want to make the first letter of the key to lower case.

For example: the key is Title then it should be title; for key PublishDate it should be publishDate and if the key is Publish_Date then it should be publish_Date and so on.

The object can be more complex depending on the data received form the server

 [ { "clientId":1, "Title":"Test", "Message":"fdsf", "Image":"", "PublishDate":"Feb 5 2020 12:00AM", "UserID":null, "authorName":"fdsfd", "announceType":"Admin", "IsAdmin":0, "TimeAgo":"1 days" }, { "clientId":1, "Title":"Test", "Message":"testing", "Image":"", "PublishDate":"Feb 5 2020 12:00AM", "UserID":null, "authorName":"Lorem Ipsum", "announceType":"Admin", "IsAdmin":0, "TimeAgo":"1 days" }, { "clientId":1, "Title":"Test", "Message":"testing ", "Image":"", "PublishDate":"Feb 5 2020 12:00AM", "UserID":null, "authorName":"Lorem Ipsum", "announceType":"CEO", "IsAdmin":0, "TimeAgo":"1 days" } ]

You can .map() each object to a new object created using Object.fromEntries() . This method takes an array of [key, value] pairs which you can get from using Object.entries() on each object within your .map() method. For each key in the entries, you can make its first letter lowercase.

See example below:

 const data = [ { "clientId":1, "Title":"Test", "Message":"fdsf", "Image":"", "PublishDate":"Feb 5 2020 12:00AM", "UserID":null, "authorName":"fdsfd", "announceType":"Admin", "IsAdmin":0, "TimeAgo":"1 days" }, { "clientId":1, "Title":"Test", "Message":"testing", "Image":"", "PublishDate":"Feb 5 2020 12:00AM", "UserID":null, "authorName":"Lorem Ipsum", "announceType":"Admin", "IsAdmin":0, "TimeAgo":"1 days" }, { "clientId":1, "Title":"Test", "Message":"testing ", "Image":"", "PublishDate":"Feb 5 2020 12:00AM", "UserID":null, "authorName":"Lorem Ipsum", "announceType":"CEO", "IsAdmin":0, "TimeAgo":"1 days" } ]; const lowerCase = str => str[0].toLowerCase() + str. slice(1); const res = data.map( obj => Object.fromEntries(Object.entries(obj).map( ([k, v]) => [lowerCase(k), v]) ) ); console.log(res);
 .as-console-wrapper { max-height: 100% !important;} /* ignore */

Currently, Object.fromEntries() does have limited browser support , however, it can be easily polyfilled. An alternative to it could be to use Object.assign() and map each entry to an object, which you spread to then assign to a larger object:

 const data = [ { "clientId":1, "Title":"Test", "Message":"fdsf", "Image":"", "PublishDate":"Feb 5 2020 12:00AM", "UserID":null, "authorName":"fdsfd", "announceType":"Admin", "IsAdmin":0, "TimeAgo":"1 days" }, { "clientId":1, "Title":"Test", "Message":"testing", "Image":"", "PublishDate":"Feb 5 2020 12:00AM", "UserID":null, "authorName":"Lorem Ipsum", "announceType":"Admin", "IsAdmin":0, "TimeAgo":"1 days" }, { "clientId":1, "Title":"Test", "Message":"testing ", "Image":"", "PublishDate":"Feb 5 2020 12:00AM", "UserID":null, "authorName":"Lorem Ipsum", "announceType":"CEO", "IsAdmin":0, "TimeAgo":"1 days" } ]; const lowerCase = str => str[0].toLowerCase() + str. slice(1); const res = data.map( obj => Object.assign({}, ...Object.entries(obj).map( ([k, v]) => ({[lowerCase(k)]: v}) )) ); console.log(res);
 .as-console-wrapper { max-height: 100% !important;} /* ignore */

for (let key in obj) {
  if (obj.hasOwnProperty(key)) {
    const newKey = key[0].toLowerCase() + key.substr(1);
    if (!obj.hasOwnProperty(newKey)) {
      obj[newKey] = obj[key];
      delete obj[key];
    }    
  }
}

Edit:

I'm not questioning what you want to achieve by doing this.

Also, it's worth noting that this will put the new property to the "end" of the object.

Edit 2:

Removed the break; from my original answer, as I thought you just wanted the first property to be amended. This version will amded all properties.

Taking your question literally, this code will lowerCase the first alphabetic char, regardless where it starts

 const data = [ { "clientId":1, "0 Title":"Test", " 000Message":"fdsf", "Image":"", "PublishDate":"Feb 5 2020 12:00AM", "UserID":null, "authorName":"fdsfd", "announceType":"Admin", "IsAdmin":0, "00000 TimeAgo":"1 days" }, { "clientId":1, "Title":"Test", "Message":"testing", "Image":"", "PublishDate":"Feb 5 2020 12:00AM", "UserID":null, "authorName":"Lorem Ipsum", "announceType":"Admin", "IsAdmin":0, "TimeAgo":"1 days" }, { "clientId":1, "Title":"Test", "Message":"testing ", "Image":"", "PublishDate":"Feb 5 2020 12:00AM", "UserID":null, "authorName":"Lorem Ipsum", "announceType":"CEO", "IsAdmin":0, "TimeAgo":"1 days" } ]; const re = /([^AZ]+)?([AZ]{1})(.*)/ const dat = obj => { let newobj = {} Object.keys(obj).forEach(key => newobj[key.replace(re,function(_,a,b,c,d) { return (a!=undefined?a:"")+b.toLowerCase() + c })] = obj[key]); return newobj; }; console.log(data.map(entry => dat(entry)))

This will work

 const data = [ { "clientId":1, "Title":"Test", "Message":"fdsf", "Image":"", "PublishDate":"Feb 5 2020 12:00AM", "UserID":null, "authorName":"fdsfd", "announceType":"Admin", "IsAdmin":0, "TimeAgo":"1 days" }, { "clientId":1, "Title":"Test", "Message":"testing", "Image":"", "PublishDate":"Feb 5 2020 12:00AM", "UserID":null, "authorName":"Lorem Ipsum", "announceType":"Admin", "IsAdmin":0, "TimeAgo":"1 days" }, { "clientId":1, "Title":"Test", "Message":"testing ", "Image":"", "PublishDate":"Feb 5 2020 12:00AM", "UserID":null, "authorName":"Lorem Ipsum", "announceType":"CEO", "IsAdmin":0, "TimeAgo":"1 days" } ]; let test = data.map(t => dat(t)) function dat(obj) { var key, keys = Object.keys(obj); var n = keys.length; var newobj = {} while (n--) { key = keys[n]; newobj[key.charAt(0).toLowerCase() + key.slice(1)] = obj[key]; } return newobj } console.log(test)

Update: Added Alternate method using forEach .

Using reduce , Object.keys , toLowerCase and template strings

 const process = data => data.map(item => Object.keys(item).reduce( (acc, key) => ( (acc[`${key[0].toLowerCase()}${key.slice(1)}`] = item[key]), acc ), {} ) ); const processAlt = data => data.map( item => ( (obj = {}), Object.keys(item).forEach( key => (obj[`${key[0].toLowerCase()}${key.slice(1)}`] = item[key]) ), obj ) ); const data = [ { clientId: 1, Title: "Test", Message: "fdsf", Image: "", PublishDate: "Feb 5 2020 12:00AM", UserID: null, authorName: "fdsfd", announceType: "Admin", IsAdmin: 0, TimeAgo: "1 days" }, { clientId: 1, Title: "Test", Message: "testing", Image: "", PublishDate: "Feb 5 2020 12:00AM", UserID: null, authorName: "Lorem Ipsum", announceType: "Admin", IsAdmin: 0, TimeAgo: "1 days" }, { clientId: 1, Title: "Test", Message: "testing ", Image: "", PublishDate: "Feb 5 2020 12:00AM", UserID: null, authorName: "Lorem Ipsum", announceType: "CEO", IsAdmin: 0, TimeAgo: "1 days" } ]; console.log(process(data)); console.log(processAlt(data));

Using some destructuring

const lowerCaseKeys = obj => Object.fromEntries(
    Object.entries(obj).map(([[firstLetter, ...rest], value]) => 
      [firstLetter.toLowerCase() + rest.join(''), value])
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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