简体   繁体   中英

Javascript remove object keys that are not in both objects with Lodash?

So, I have this two objects:

const obj1 = {
  foo: 'Foo',
  bar: {
    baz: 'Baz',
  }
}

const obj2 = {
  foo: 'Foo',
  bar: {
    baz: 'Baz',
    zip: 'Zip'
  },
}

I want to remove "zip" from obj2 since it's not in obj1. Is there a way to do this with lodash?

EDIT: If a property is an object, it will be an object in both of them. There can't be a string with the same key of an object in the other one.

The use case is, I have a translation file and after some processing, I need to remove the ones that are no longer needed. So if I delete them in the original object (ie obj1) they have to be removed from the other ones (in this case, obj2.

If you are open to using additional libraries, I can recommend looking into deep-diff :

 const obj1 = { foo: 'Foo', bar: { baz: 'Baz', } } const obj2 = { foo: 'Foo', bar: { baz: 'Baz', zip: 'Zip' }, } DeepDiff.observableDiff(obj2, obj1, d => { DeepDiff.applyChange(obj2, obj1, d) }); console.log(obj1) console.log(obj2)
 <script src="https://cdn.jsdelivr.net/npm/deep-diff@1/dist/deep-diff.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM