DanFragoso DanFragoso - 1 year ago 69
Javascript Question

Merge two unordered objects with different keys but same value?

Merge objects like obj1 and obj2 to get obj3 in javascript.

obj1 = [{fruit: 'watermelon', sweetness: 3},{fruit: 'banana', sweetness: 4},{fruit: 'apple', sweetness: 5}]
obj2 = [{fruit_name: 'apple', color: 'red'},{fruit_name: 'banana', color:'yellow'},{fruit_name: 'watermelon', color:'green'}]

obj3 = [{fruit_name: 'apple', color: 'red', sweetness: 5},{fruit_name: 'banana', color:'yellow', sweetness: 4},{fruit_name: 'watermelon', color:'green', sweetness: 3}]

Answer Source

Your data structure is incorrect. You can not save "'fruit: 'watermelon'" (key, value pair) in an array.

It would give an error: Uncaught SyntaxError: Unexpected token :

I am assuming what you are trying to do is:

obj1 = [{fruit: 'watermelon', sweetness: 3},{fruit: 'banana', sweetness: 4},{fruit: 'apple', sweetness: 5}]
  obj2 = [{fruit_name: 'apple', color: 'red'},{fruit_name: 'banana', color:'yellow'},{fruit_name: 'watermelon', color:'green'}]
  obj3 = [];
  
for (i = 0; i < obj1.length; i++) {
  for (j = 0; j < obj2.length; j++) {
    if (obj1[i].fruit === obj2[j].fruit_name) {
      var temp = {
        fruit_name: obj2[j].fruit_name,
        color: obj2[j].color,
        sweetness: obj1[i].sweetness
      }
      obj3.push(temp);
    }
  }
}

console.log(obj3);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download