Merge objects like obj1 and obj2 to get obj3 in javascript.
obj1 = [{fruit: \'watermelon\', sweetness: 3},{fruit: \'banana\', sweetness: 4},{fruit: \'apple\', sw
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);