其他分享
首页 > 其他分享> > 使用lodash把数组对象中相同的字段的值合并

使用lodash把数组对象中相同的字段的值合并

作者:互联网

假如是在vue中使用该方法:

<script>
export default {
    created(){
         let fruitSamples = [
      { id: 1, type: 'apples', samples: [{ id: 1, name: 1 }] },
      { id: 2, type: 'bananas', samples: [{ id: 2, name: 2 }] },
      { id: 3, type: 'pears', samples: [{ id: 3, name: 3 }] },
      { id: 1, type: 'apples', samples: [{ id: 11, name: 11 }] },
    ]

        this.mergeArrObj(fruitSamples,'type');
},

methods:{
    // fruitSamples需要合并的数组对象,type需要依据哪个属性合并
  mergeArrObj(fruitSamples,type){
    function customizer(objValue, srcValue) {
      if (_.isArray(objValue)) {
        return objValue.concat(srcValue)
      }
    }

    // 传需要处理的参数过去
    let test = _(fruitSamples)
      .flatten()
      .groupBy(type)
      .map(
        _.spread((...values) => {
            console.log("value是多少")
            console.log(...values);
          return _.mergeWith(...values, customizer)
        }),
      )
      .value()
      console.log("test为多少")
   console.log(test)
 // ->结果如下:
 [
  { id: 1, type: 'apples', samples: [1, 2, 3, 5, 2, 9, 11, 2, 33] },
  { id: 2, type: 'bananas', samples: [1, 2, 7, 1, 7, 7, 17, 2, 67] },
  { id: 3, type: 'pears', samples: [1, 2, 3, 12, 21, 32, 91, 22, 34] }
]
  }
}

}
</script>

标签:console,lodash,fruitSamples,合并,数组,samples,type,id,log
来源: https://blog.csdn.net/qq_42931285/article/details/121304460