Search code examples
javascriptreactjslodashnested-objectcustomizer

How to write customizer function for lodash _.mergeWith third argument in this situation?


I have two objects like that:

var obj3 = {
    customer_id: 1,
    products: { id: 1, name: "Car" },
  };

  var obj4 = {
    customer_id: 1,
    products: { id: 2, name: "Dress" },
  };

and the expected object is:

result = {
    customer_id: 1,
    products: [
      { id: 1, name: "Car" },
      { id: 2, name: "Dress" },
    ],
  };

How can i write function customizer(){} in this situation? Thanks so much for your help, and i'll be welcome for other solution with different way.


Solution

  • Merge the objects to a new object (the {}). Set the default values of the merged values to empty arrays. If the key is products concat them. If not return undefined, so the standard logic of _.merge() would be used:

    const obj3 = { customer_id: 1, products: { id: 1, name: "Car" }, };
    const obj4 = { customer_id: 1, products: { id: 2, name: "Dress" }, };
    
    const result = _.mergeWith({}, obj3, obj4, (v1 = [], v2 = [], key) =>
      key === 'products' ? v1.concat(v2) : undefined
    )
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>