我具有以下代碼以兩個對象合併兩個對象在javascript
合併代碼:
var goals = {1:"first",2:"second"};
var pages = {1:"page1",2:"page2"};
var result = {};
for(var goal in goals){
for(var page in pages){
if(page.hasOwnProperty(goal)){
result[goal] = {"goal":goals[goal],"page":pages[page]};
}
}
}
console.log(result);
預期結果:
result = {1:{"goal":"first","page":"page1"},2:{"goal":"second","page":"page2"}};
代碼工作正常和獲得預期的產出。
任何建議改變它,或者最好與此同行。
改進代碼
var result = {};
for(var goal in goals){
if(pages.hasOwnProperty(goal)){
result[goal] = {"goal":goals[goal],"page":pages[goal]};
}
}
使用hasOwnProperty() –
@ lukas.pukenis編輯代碼。它現在正確嗎? – karthick
如果頁面具有更多屬性,那麼它將不會顯示在您的輸出中。這種情況會發生嗎? – eggward