Merge two unordered objects with different keys but same value?

前端 未结 5 1959
谎友^
谎友^ 2021-01-28 02:05

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

obj1 = [{fruit: \'watermelon\', sweetness: 3},{fruit: \'banana\', sweetness: 4},{fruit: \'apple\', sw         


        
5条回答
  •  星月不相逢
    2021-01-28 02:53

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

提交回复
热议问题