0

I having the following code to merge the two objects

Code:

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);

Expected result:

result = {1:{"goal":"first","page":"page1"},2:{"goal":"second","page":"page2"}};

code is working fine and getting the expected output.

Any suggestion to change it or it is better to go with this.

Improved code

    var result = {};

    for(var goal in goals){
     if(pages.hasOwnProperty(goal)){
        result[goal] = {"goal":goals[goal],"page":pages[goal]};
      }
    }
3
  • @lukas.pukenis Edited the code.is it correct now? Commented Oct 24, 2013 at 13:02
  • if pages has more properties then it will not show up in your output. Will this scenario happen? Commented Oct 24, 2013 at 13:03
  • thanks all for answering Commented Oct 25, 2013 at 6:17

3 Answers 3

1

Your solution is O(m*n). The following is of 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];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Could be more efficient & complete still: while looping over one object, check if those keys exist in the second. Delete the property if it does, after adding it to the result, of course (cf my answer). You're also not filtering (hasOwnProperty) the loop. It's redundant 9/10 cases, true, but you never know how the OP is going to use your code
1

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

var result = _.extend(goals, pages);

1 Comment

I highly recommend underscore as well
0

You need to use obj.hasOwnProperty().

When you do for x in y it provides you all the properties and methods of an object.

obj.hasOwnProperty() tells you if a property is a direct property on the object or in it's prototype(if returns false).

Your extend function should look like this:

function extend(src, dst){
    for(var key in dst)
        if(dst.hasOwnProperty(key))
            src[key] = dst[key];
    return src;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.