繁体   English   中英

lodash:比较两个对象

[英]lodash: compare two objects

我想通过lodash做到这一点:

first = { one: 1, two: 2, three: 3 }

second = { three: 3, one: 1 }

_.CustomisEqual(first, second);
// → true

third = { one: 1, two: 2, three: 3 }

fourth = { three: 4, one: 1 }

_.CustomisEqual(third, fourth);
// → false

但是通常的_.isEqual不支持这种比较方法,有没有办法通过lodash进行这种比较?

 function CustomisEqual(objOne, objTwo) { return !!_([objOne]).filter(objTwo).size(); } first = { one: 1, two: 2, three: 3 } second = { three: 3, one: 1 } var resOne = CustomisEqual(first, second); console.log('resOne ', resOne); // → true third = { one: 1, two: 2, three: 3 } fourth = { three: 4, one: 1 } var resTwo = CustomisEqual(third, fourth); console.log('resTwo ', resTwo); // → false 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.js"></script> 

本质上是这样的:

 // mock lodash var _ = {} // create custom lodash method _.CustomisEqual = function (a, b) { // get array of the keys in object var aKeys = Object.keys(a) var bKeys = Object.keys(b) // get the array of the keys with the smallest length var minKey = (aKeys.length > bKeys.length ? bKeys : aKeys) // get the obejct with the smallest and greatest length var minObj = (aKeys.length > bKeys.length ? b : a) var maxObj = (a === minObj ? b : a) // get the length from the smallest length array of the keys var minLen = Math.min(aKeys.length, bKeys.length) // iterate through the smallest object for (var i = 0; i < minLen; i++) { var currentKey = minKey[i] // ignore values that are in one but not the other if (maxObj[currentKey] !== undefined && // compare defined values of both objects maxObj[currentKey] !== minObj[currentKey]) { // return false if they don't match return false } } // otherwise, they do match, so return true return true } var first = { one: 1, two: 2, three: 3 } var second = { three: 3, one: 1 } console.log(_.CustomisEqual(first, second)) // → true var third = { one: 1, two: 2, three: 4 } var fourth = { three: 3, one: 1 } console.log(_.CustomisEqual(third, fourth)) // → false 

希望对您有所帮助!

我认为以下解决方案可能有用。

 var first = { one: 1, two: 2, three: 3 }; var second = { three: 3, one: 1 }; var third = { one: 1, two: 2, three: 3 }; var fourth = { three: 4, one: 1 }; function customIsEquals(first,second) { var ret = true; _.forEach(second,function(value, key){ if(first[key]!==value){ ret = false; } }); return ret; } _.mixin({ 'customIsEquals': customIsEquals }); console.log(_.customIsEquals(first,second)); console.log(_.customIsEquals(third,fourth)); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script> 

暂无
暂无

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

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