这不是一个太复杂的对象。在转换为字符串之前,它不是 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" });