1

I have two objects like so:

originalObj:

{
    name: "Jane",
    fullName: "Jane Doe"
    nickname: "Janey"
    ...etc...
}

updatedObj:

{
    name: "Jane",
    fullName: "Jane Dawn", //<--this value changed
    nickname: "Janey"
    ...etc..
}

With lodash 4, how can I compare both objects and just return the updated values with key?

So, for example, I would expect to see:

{
    fullName: "Jane Dawn",
        ...etc...
}

My use case is that I want to show a "before" and "after" view to a user of existing database data and user-updated form data before submitting to a server.

redshift
  • 4,815
  • 13
  • 75
  • 138

1 Answers1

3

If it's flat object, ie no nested objects or arrays, you can use _.pickBy() on the updated object, and take every property that is not equal to the similar property from the original object:

const originalObj = {"name":"Jane","fullName":"Jane Doe","nickname":"Janey"}
const updatedObj = {"name":"Jane","fullName":"Jane Dawn","nickname":"Janey"}

const result = _.pickBy(updatedObj, (v, k) => !_.isEqual(originalObj[k], v))

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>

If you need to compare nested objects, use a package, such as deep-object-diff .

Ori Drori
  • 183,571
  • 29
  • 224
  • 209