我有一個服務對象,我需要將它的日誌附加到ServiceLogEntries.ID等於ServiceID的地方。如何將元素添加到JavaScript對象?
var Services = {
"result": [
{
"ID": 150779,
"ServiceRenderedID": 1,
"ServiceTypeName": "Health Risk Assessment",
"PackageID": 13
},
{
"ID": 150778,
"ServiceRenderedID": 1,
"ServiceTypeName": "Health Risk Assessment",
"PackageID": 13
}
]
};
var ServiceLogEntries = {
"ServiceLogEntries": [
{
"LogID": 229500.0,
"LogStamp": "2015-12-08T18:29:16.137",
"LogServerUser": "Webuser",
"LogActionType": "I",
"ID": 150779
},
{
"LogID": 229501.0,
"LogStamp": "2015-12-08T18:30:07.32",
"LogServerUser": "Webuser",
"LogActionType": "U",
"ID": 150779
},
{
"LogID": 229500.0,
"LogStamp": "2015-12-08T18:29:16.137",
"LogServerUser": "Webuser",
"LogActionType": "I",
"ID": 150778
},
{
"LogID": 229501.0,
"LogStamp": "2015-12-08T18:30:07.32",
"LogServerUser": "Webuser",
"LogActionType": "U",
"ID": 150778
}
]
};
結果應該看起來像下面的代碼,其中元素「ServiceLogEntires」是通過附加相應的項目創建的。
var Service = {
"result": [
{
"ID": 150779,
"ServiceRenderedID": 1,
"ServiceTypeName": "Health Risk Assessment",
"PackageID": 13
},
{
"ID": 150778,
"ServiceRenderedID": 1,
"ServiceTypeName": "Health Risk Assessment",
"PackageID": 13,
"ServiceLogEntries": [
{
"LogID": 229500.0,
"LogStamp": "2015-12-08T18:29:16.137",
"LogServerUser": "Webuser",
"LogActionType": "I",
"ID": 150778
},
{
"LogID": 229501.0,
"LogStamp": "2015-12-08T18:30:07.32",
"LogServerUser": "Webuser",
"LogActionType": "U",
"ID": 150778
}
]
}
]
我開始通過這是很容易做到的對象循環,但我需要得到整個元素"ServiceLogEntries": [{...}]
。
for (var i = 0; i < Service.result.length; i++) {
var parent = Service.result[i];
for (var a = 0; a < ServiceLogEntries.ServiceLogEntries.length; a++) {
var child = ServiceLogEntries.ServiceLogEntries[a];
if (child.ID === parent.ID) {
parent.push(child);
}
}
}
和WH結果你會得到什麼?你知道jsfiddle嗎? – helle
https://jsfiddle.net/t3twxgfs/ –