Merge two unordered objects with different keys but same value?

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

    let obj1 = [{fruit: 'watermelon', sweetness: 3},{fruit: 'banana', sweetness: 4},{fruit: 'apple', sweetness: 5}];
    let obj2 = [{fruit_name: 'apple', color: 'red'},{fruit_name: 'banana', color:'yellow'},{fruit_name: 'watermelon', color:'green'}];
    
    function regulate(a) {
      return a.map(v => {
        if (v.fruit) {
            v.fruit_name = v.fruit;
            delete v.fruit;
         }
         return v;
      });
    }
    
    
    let a = [].concat(regulate(obj1), regulate(obj2));
    
    let merged = [];
    a.reduce((m, v) => {
      let f = m.filter(v2 => v2.fruit_name === v.fruit_name);
      if (f.length > 0) {
        Object.assign(f[0], v);
      } else {
        m.push(v);
      }
      return m;
    }, merged);
    
    console.log(merged);
    

提交回复
热议问题