Convert returned JSON Object Properties to (lower

2019-02-03 00:29发布

I have JSON returned from an API like so:

Contacts: [{ GivenName: "Matt", FamilyName:"Berry" }]

To keep this consistent with my code style (camelCase - lower case first letter) I want to transform the array to produce the following:

 contacts: [{ givenName: "Matt", familyName:"Berry" }]

Whats the easiest/best way to do this? create a new Contact object and iterate over all the contacts in the returned array?

var jsonContacts = json["Contacts"],
    contacts= [];

_.each(jsonContacts , function(item){
    var contact = new Contact( item.GivenName, item.FamilyName );
    contacts.push(contact);
});

or can I map the original or transform it somehow?

13条回答
家丑人穷心不美
2楼-- · 2019-02-03 01:01

Here's a reliable, recursive function that will properly camelCase all of a JavaScript object's properties:

function toCamel(o) {
  var newO, origKey, newKey, value
  if (o instanceof Array) {
    return o.map(function(value) {
        if (typeof value === "object") {
          value = toCamel(value)
        }
        return value
    })
  } else {
    newO = {}
    for (origKey in o) {
      if (o.hasOwnProperty(origKey)) {
        newKey = (origKey.charAt(0).toLowerCase() + origKey.slice(1) || origKey).toString()
        value = o[origKey]
        if (value instanceof Array || (value !== null && value.constructor === Object)) {
          value = toCamel(value)
        }
        newO[newKey] = value
      }
    }
  }
  return newO
}

Test:

var obj = {
  'FirstName': 'John',
  'LastName': 'Smith',
  'BirthDate': new Date(),
  'ArrayTest': ['one', 'TWO', 3],
  'ThisKey': {
    'This-Sub-Key': 42
  }
}

console.log(JSON.stringify(toCamel(obj)))

Output:

{
    "firstName":"John",
    "lastName":"Smith",
    "birthDate":"2017-02-13T19:02:09.708Z",
    "arrayTest": [
        "one", 
        "TWO", 
        3
    ],
    "thisKey":{
        "this-Sub-Key":42
    }
}
查看更多
登录 后发表回答