Merge two unordered objects with different keys but same value?

前端 未结 5 1955
谎友^
谎友^ 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:44

    You can first create a hashtable by merging similar objects using #forEach and then extract the required array using a #map() function - see demo below:

    var 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'}], hash = {};
    
    // function to create a hashtable
    function classify(e) {
       if(hash[e.fruit] || hash[e.fruit_name]) {
         Object.keys(e).forEach(function(c){
            hash[e.fruit || e.fruit_name][c] = e[c];
         });
       } else {
         hash[e.fruit_name || e.fruit] = e;
       }
    }
    
    // add to hash
    obj1.forEach(classify);
    obj2.forEach(classify);
    
    // extract the result
    var obj3 = Object.keys(hash).map(function(e){
      delete hash[e]['fruit'];
      return hash[e];
    });
    
    console.log(obj3);
    .as-console-wrapper{top:0;max-height:100%!important;}

提交回复
热议问题