简体   繁体   English

Lodash isEqual - 如何获取不同对象的键

[英]Lodash isEqual - How to get keys of objects that differ

I'm trying to obtain an array of keys, that were different as a result of comparing two objects.我正在尝试获取一个键数组,由于比较两个对象而不同。 I was only able to do it using isEqualWith and mapKeys , like so:我只能使用isEqualWithmapKeys来做到这一点,如下所示:

 const differencies = []; const objA = { a: 1, b: 2, c: 3 }; const objB = { a: 1, b: 2, c: 100 }; function customizer(objOne, objTwo) { if (lodash.isEqual(objOne, objTwo)) { return true; } lodash.mapKeys(objOne, (value, key) => { if (value !== objTwo[key]) { differencies.push(key); } }); return false; } lodash.isEqualWith(objA, objB, customizer); console.log(differencies);
 <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script> <script>const lodash = _;</script>

Question is : Is there a better way to get keys of objects that differ using lodash?问题是有没有更好的方法来获取使用 lodash 不同的对象的键?

Since you only need to compare objects where the keys are identical but values might differ, you can leverage keys() or keysIn() (if you want to also traverse the prototype chain) and remove all entries that do not have a matching value with filter() .由于您只需要比较键相同但值可能不同的对象,因此您可以利用keys()keysIn() (如果您还想遍历原型链)并删除所有没有匹配值的条目filter()

 const objA = { a: 1, b: 2, c: 4 }; const objB = { a: 1, b: 2, c: 100 }; const differencies = lodash.filter( lodash.keys(objA), key => objA[key] !== objB[key] ); console.log(differencies);
 <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script> <script>const lodash = _;</script>

Alternatively using chaining syntax :或者使用链接语法

 const objA = { a: 1, b: 2, c: 4 }; const objB = { a: 1, b: 2, c: 100 }; const differencies = lodash(objA) .keys() .filter(key => objA[key] !== objB[key]); console.log(differencies);
 <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script> <script>const lodash = _;</script>

For this sort of functionality, Lodash might be an overkill.对于这种功能,Lodash 可能是矫枉过正。 Simple JavaScript equivalent is Object.keys() and Array#filter() :简单的 JavaScript 等价物是Object.keys()Array#filter()

 const objA = { a: 1, b: 2, c: 4 }; const objB = { a: 1, b: 2, c: 100 }; const differencies = Object.keys(objA) .filter(key => objA[key] !== objB[key]); console.log(differencies);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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