How to merge objects with Lodash, but replace arrays values?

Viewed 1330

I'm trying to replace arrays of an old object with values from a new object which has arrays... I guess it will make sense when you see an example and desire result:

https://jsfiddle.net/redlive/9coq7dmu/

const oldValues = {
    a: 1,
  b: [2, 21, 22, 23],
  c: {
    d: 3,
    e: 4,
    f: [5, 6, 7]
  }
};

const updatedValues = {
    b: [],
    c: {
    f: [8]
  }
}

const result = _.merge( oldValues, updatedValues );
console.log(result);

/* Desire result:

{
  a: 1,
  b: [],
  c: {
    d: 3,
    e: 4,
    f: [8]
  }
} 

*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>

1 Answers

Use _.mergeWith(), and if the 2nd value is an array, return it. If not return undefined, and let merge handle it:

const oldValues = {"a":1,"b":[2,21,22,23],"c":{"d":3,"e":4,"f":[5,6,7]}};
const updatedValues = {"b":[],"c":{"f":[8]}};

const result = _.mergeWith(oldValues, updatedValues, (a, b) => 
  _.isArray(b) ? b : undefined
);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>

Related