5

当我序列化一个 ASP.NET MVC 表单时,我得到这个:

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

但我想要这个,以便它符合 JS 编码约定:

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

如何获取对象并将每个属性的第一个字符小写?

4

3 回答 3

4

简单的方法是对您的对象进行迭代:

var newObj = {};
for (var p in o) {
    newObj[p.substring(0,1).toLowerCase()+p.substring(1)] = o[p];
}
于 2012-10-30T13:38:53.507 回答
2

还必须检查 hasOwnProperty,并删除以前的属性

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 ];
  }
}
于 2012-10-30T13:47:45.317 回答
1

将这些东西当作字符串并使用 Reg exps power 不是更好吗?

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

于 2017-08-16T10:21:37.093 回答