我有以下代码来合并两个对象
代码:
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]};
}
}