1

I have and object1 with a unknown key name and i need to merge with other object2. The secure point is that unknown key is not present in the object2 so, never gonna be key names conflicts.

var object1 = {
 id: 1,
 name: "myname",
 boleanSample : true
}


var object2 = {
 unknownKeyName : "UnknownValue"
}

I want to merge object2 into object1 and get this

var object1 = {
 id: 1,
 name: "myname",
 boleanSample : true,
 unknownKeyName = "UnknownValue"
}

Please, vanilla Javascript only. If the response require the creation of an new object3 is totally fine :)

PD: I checked these links before post the question:

No duplication at all for those :)

Community
  • 1
  • 1
Héctor León
  • 2,210
  • 2
  • 23
  • 36

3 Answers3

2

Use Object.keys with Array#forEach

var object1 = {
  id: 1,
  name: "myname",
  boleanSample: true,
};

var object2 = {
  unknownKeyName: "UnknownValue" //correct typo here
};
Object.keys(object2).forEach(function(key) {
  object1[key] = object2[key];
});
console.log(object1);
Rayon
  • 36,219
  • 4
  • 49
  • 76
  • Ok guys thank you so much but what can i do now ? Niet the Dark Absol comment a valid solution, but @gurvinder372 and Rayon posted a valid solution also. Maybe some update with both ways ? And someone know which one is better/faster/performance advantage :) ? – Héctor León Jun 03 '16 at 10:29
  • @HéctorLeón, Gurvinder was quickest among all..Go with his post :) – Rayon Jun 03 '16 at 10:31
0

This merge function should do it. Just remember to add the object you want to append two first.

var object1 = {
 id: 1,
 name: "myname",
 boleanSample : true
}


var object2 = {
 unknownKeyName : "UnknownValue"
}

function mergeObjects(a,b){
  for(var bi in b) {
    if(b.hasOwnProperty(bi)) {
      if(typeof a[bi] === "undefined") {
        a[bi] = b[bi];
      }
    }
  }
}
mergeObjects(object1,object2);
console.log(object1);
Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28
0

Step I: loop over the properties.

Step II: try and check if object

Step III: if true, stimulate function on obj[prop] and check, else just take check.

Step IV: if there was an error obj[prop] = check;

Step V: return obj

/*functions*/
function objectConcat(o1, o2) {
  for (var v in o2) {
    try {
      o1[v] = (o2[v].constructor == Object) ? objectConcat(o1[v], o2[v]) : o2[v];
    } catch (e) {
      o1[v] = o2[v];
    }
  }
  return o1;
}

/*objects*/
var object1 = {
  id: 1,
  name: "myname",
  boleanSample: true,
}

var object2 = {
  unknownKeyName: "UnknownValue" /*mistake straighten*/
}

/*code*/

console.log(objectConcat(object2, object1));