Josh Kodroff Josh Kodroff - 1 year ago 63
Javascript Question

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?

Answer Source

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 ];
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download