循环以将数据添加到复杂的JSON对象

时间:2012-09-11 22:58:57

标签: json loops

我有一个像这样的复杂JSON对象:

var requestData = { __batchRequests: [ { __changeRequests: [
{ requestUri: "Customers", method: "POST", headers: { "Content-ID": "1" }, data: { 
    CustomerID: 400, CustomerName: "John"
}  }
] } ] };           

我正在尝试做两件事:

  1. 声明此对象,但变量数据为空

  2. 使用循环,动态添加项目到数据对象,

  3. 我该怎么做?

2 个答案:

答案 0 :(得分:1)

对于问题的第一部分,您可以使用空关联数组初始化data

var requestData = { __batchRequests: [ { __changeRequests: [
{ requestUri: "Customers", method: "POST", headers: { "Content-ID": "1" }, data: {}  }
] } ] };    

下一部分假定您可以使用jQuery,也许是错误的。它还假定您有一个包含所有相关键值对的数组。

var customerDeetsArray =[{CustomerID: 400}, {CustomerName: "John"}]; 

for (var i in customerDeetsArray) {
  requestData.data = $.extend(requestData.data, customerDeetsArray[i]);
}

参见使用console.debug的工作示例:

http://jsfiddle.net/4Rh72/6/

答案 1 :(得分:1)

这不是一个太复杂的对象。并且它不是JSON,直到它被转换为字符串。 现在,它只是简单的'JS对象和数组。

将其分解为其元素可能如下所示:

var requestData = {};
requestData.__batchRequests = [];
requestData.__batchRequests[0] = {};
requestData.__batchRequests[0].__changeRequests = [];
requestData.__batchRequests[0].__changeRequests[0] = {};
requestData.__batchRequests[0].__changeRequests[0].requestUri = "Customers";
requestData.__batchRequests[0].__changeRequests[0].method = "POST";
requestData.__batchRequests[0].__changeRequests[0].headers = { "Content-ID" : "1" };
requestData.__batchRequests[0].__changeRequests[0].data = {};

除了重复之外,你看到了什么? 就个人而言,我看到__changeRequests[0]是一个简单的对象:

var changeRequest = {
    requestUri : "Customers",
    method : "POST",
    headers : { "Content-ID" : "1" },
    data : {}
};

我也看到我可以将其推送到我的变更请求数组中:

requestData.__batchRequests[0].__changeRequests.push(changeRequest);

右?

我也知道我的changeRequest变量仍然指向我刚刚添加到数组中的变量,并且我在对象上更改的内容也将在数组对对象的引用中显示为已更改:< / p>

changeRequest.data.CustomerName = "Bob";
changeRequest.data.CustomerID = "204";


requestData.__/*...*/changeRequests[0].data.CustomerName; // Bob

那么如何为自己编写一些辅助函数呢?

function extend (obj, additions) {
    var key;
    for (key in obj) { if (additions.hasOwnProperty(key)) {
        obj[key] = additions[key];
    }
}

function makeChangeRequest (url, method, headers, data) {
    var request = {
        requestUri : url,
        method : method,
        headers : {},
        data : {}
    };

    extend(request.headers, headers);
    extend(request.data, data);

    return request;
}

function getBatch (num) { return requestData.__batchRequests[num]; }


var changeReq = makeChangeRequest("Customers",
                                  "POST",
                                  { "Content-ID" : "1" },
                                  { CustomerName : "Bob", CustomerID : "2012" });

var batch = getBatch(0);

batch.__changeRequests.push(changeReq);

如果您想稍后向changeReq.data添加更多数据:

extend(changeReq.data, { Address : "33 Nowhere Rd.", City : "Splitsville" });