9

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 Answer 1

30

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.