我有以下代码来合并两个对象
代码:
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]};
}
}
答案 0 :(得分:1)
您的解决方案是O(m * n)。以下是O(m + n):
var goals = {1:"first",2:"second"};
var pages = {1:"page1",2:"page2"};
var result = {};
for(var x in goals){
if(!result[x])result[x] = {};
result[x].goals = goals[x];
}
for(var x in pages){
if(!result[x])result[x] = {};
result[x]. page = pages[x];
}
答案 1 :(得分:1)
使用Underscore.js,你会得到一个简单的单行程序:
var result = _.extend(goals, pages);
答案 2 :(得分:0)
您需要使用obj.hasOwnProperty()
。
执行for x in y
时,它会为您提供对象的所有属性和方法。
obj.hasOwnProperty()
告诉您属性是对象的原始属性还是原型(如果返回false)。
您的扩展功能应如下所示:
function extend(src, dst){
for(var key in dst)
if(dst.hasOwnProperty(key))
src[key] = dst[key];
return src;