简体   繁体   中英

How do I clone a JavaScript object from PascalCase properties to camelCase properties (in JavaScript)?

When I serialize an ASP.NET MVC form, I get this:

{
  DestinationId: "e96dd00a-b042-41f7-bd59-f369904737b6",
  ...
}

But I want this, so that it's consistent with JS coding conventions:

{
  destinationId: "e96dd00a-b042-41f7-bd59-f369904737b6",
  ...
}

How do I take an object and lower-case the first character of each property?

Simple way is make iteration over your object:

var newObj = {};
for (var p in o) {
    newObj[p.substring(0,1).toLowerCase()+p.substring(1)] = o[p];
}

Also have to check for hasOwnProperty, and remove the previous property

var object = { DestinationId: "e96dd00a-b042-41f7-bd59-f369904737b6" }
for ( var prop in object ) {
  if ( object.hasOwnProperty( prop ) ) {
    object[ prop.substring(0,1).toLowerCase() + prop.substring(1) ] = object[ prop ];
    delete object[ prop ];
  }
}

将这些东西视为字符串并使用Reg exps power是不是更好?

JSON.parse( JSON.stringify(z).replace( /(\\"[^"])([^"]*\\"\\:)/g, function(all, head, tail) { return head.toLowerCase() + tail; } ) )

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