我从这样的API返回了JSON:

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

为了使其与我的代码风格(camelCase-小写首字母)保持一致,我想对数组进行转换,以生成以下内容:

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

最简单/最好的方法是什么?创建一个新的联系人对象并迭代返回数组中的所有联系人?

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

或者我可以映射原始数组或以某种方式转换它吗?

推荐答案

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
}

测试:

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

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

输出:

{
    "firstName":"John",
    "lastName":"Smith",
    "birthDate":"2017-02-13T19:02:09.708Z",
    "arrayTest": [
        "one", 
        "TWO", 
        3
    ],
    "thisKey":{
        "this-Sub-Key":42
    }
}

Jquery相关问答推荐

使用 Ajax 列出数据(仅显示最后的数据)

如何在Jquery和Laravel中使用请求传递两个参数给Datatable

如何从 onclick div 属性检测 Javascript 中的 control+click?

提醒未保存的表单更改

我们如何在不重新加载页面的情况下使用 javascript/jQuery 更新 URL 或查询字符串?

jQuery - 获取 ajax POST 的表单值

JQuery手风琴自动高度问题

Jquery查找所有以字符串开头的ID?

使用 JQuery 更改 :before css Select 器的宽度属性

jQuery .hide() 和 .css("display", "none") 的区别

如何重新启用 event.preventDefault?

jQuery中追加的相反

在 jquery 中启用/禁用下拉框

使用 jquery 在 radio 上单击或更改事件

检测夹点的最简单方法

使用 jQuery 获取鼠标单击图像的 X/Y 坐标

JavaScript 中的简单节流阀

你如何记录jQuery中一个元素触发的所有事件?

如何使用 jQuery Select 第一个父 DIV?

jQuery 将换行符转换为 br (nl2br 等效)