0

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

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

我正在尝试做两件事:

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

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

我该怎么做?

4

2 回答 2

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变量仍然指向我刚刚添加到数组中的变量,并且无论我在对象上所做的任何更改都将在数组对对象的引用中显示为已更改:

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" });
于 2012-09-12T00:32:43.610 回答
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/

于 2012-09-11T23:59:44.490 回答