0

我有以下代码来合并两个对象

代码:

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]};
      }
    }
4

3 回答 3

1

With Underscore.js you get a nice and simple one-liner:

var result = _.extend(goals, pages);
于 2013-10-24T13:03:48.817 回答
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];
}
于 2013-10-24T13:02:50.530 回答
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;
于 2013-10-24T13:02:07.450 回答