這並不是太複雜的對象。直到它被轉換成一個字符串,它纔是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" });
非常感謝,你的回答非常完整。 – George