简体   繁体   English

如何小写对象中键的第一个字母?

[英]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.我有一个 JavaScript 对象,我想将键的第​​一个字母变成小写。

For example: the key is Title then it should be title;例如:key 是 Title 那么它应该是 title; for key PublishDate it should be publishDate and if the key is Publish_Date then it should be publish_Date and so on.对于键 PublishDate 它应该是 publishDate 如果键是 Publish_Date 那么它应该是 publish_Date 等等。

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() .您可以.map()每个对象到使用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.此方法采用[key, value]对数组,您可以通过在.map()方法中的每个对象上使用Object.entries()来获取该数组。 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.目前, Object.fromEntries()确实有有限的浏览器支持,但是,它可以很容易地被 polyfill。 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:另一种方法是使用Object.assign()并将每个条目映射到一个对象,然后将其扩展到一个更大的对象:

 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:编辑2:

Removed the break;删除了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 .更新:添加了使用forEach替代方法。

Using reduce , Object.keys , toLowerCase and template strings使用reduceObject.keystoLowerCase和模板字符串

 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])
);

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

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