karthick
karthick

Reputation: 6178

Merging two object in javascript

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

Upvotes: 0

Views: 90

Answers (3)

subZero
subZero

Reputation: 5186

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

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

Upvotes: 1

Akshaya Shanbhogue
Akshaya Shanbhogue

Reputation: 1448

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

Upvotes: 1

lukas.pukenis
lukas.pukenis

Reputation: 13597

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;

Upvotes: 0

Related Questions