如何向对象添加数据?

时间:2016-11-18 17:18:29

标签: jquery angularjs json

我有一个API,可以接受单个数据或批量数据,然后相应地发送响应。在发送单个数据时,我发送的数据如下,

var contactId = 123;
var url = "www.abc.com";
var companyName = "ABC";
var compLink = "/abc/123/link";
var randomKey = generateRandomKey();

   $.ajax({
       url:liurl,
       type:"POST",
       data:JSON.stringify({
           "verification_key":randomKey,
           "listData" :
               [{
               "contactid":contactId,
               "url": url,
               "li_company":companyName,
               "complink":compLink
           }]
       }),
       contentType:"application/json",
       dataType:"json",
       success: function(result){
           $.each(result, function(index, element) {
               //perform operation on 'result'
           });
       }
   });

以上代码完美运行,我得到了适当的回复。现在,当我想一次验证多条记录时,listData应该是这样的,

{
    "verification_key":"d0vvNl04dk3y",
    "listData" :
        [{
        "contactid":"241",
        "url":"http://www.name.com/in/daveandrews",
        "companyName":"Devious Media",
        "complink":"/company/devious-media"
    },
    {
        "contactid":"242",
        "url":"http://www.name.com/in/something",
        "companyName":"Sol Media",
        "complink":"/company/somemedia"
    },{
        "contactid":"243",
        "url":"http://www.name.com/in/daveandrews",
        "companyName":"Mega Media",
        "complink":"/company/xyzmedia"
    }]
}

正如您所见,listData包含超过1条记录的详细信息。我无法弄清楚如何将这些多个数据耦合到一个对象并发送到API。仅供参考,contactid, url, companyName and complink的值存储在数组中。 例如:

var contactid = [1,2,3,4,5]
var companyName = ["abc","xyz","qwe","asd","zxc"];

1 个答案:

答案 0 :(得分:2)

你在寻找聪明的东西,还是这么简单?我不认为这有一个神奇的功能方法,但也许其他人比我更聪明。

假设您的数组长度相同,如下所示:

let listData = [];

for (let i=0; i < contactid.length; i++) {
    listData.push({
        contactid: contactid[i],
        url: "http://www.name.com/in/something",
        li_companyName: companyName[i],
        complink: complink[i]
    });
}

(更新如何组合新请求)

如果listData具有正确的格式,请直接将其附加到您的请求中。

$.ajax({
   url:liurl,
   type:"POST",
   data:JSON.stringify({
       "verification_key":randomKey,
       "listData" : listData
   }),
   contentType:"application/json",
   dataType:"json",
   success: function(result){
       $.each(result, function(index, element) {
           //perform operation on 'result'
       });
   }

});