JS - Lodash工具库的使用详解15(深比较,判断是否包含某属性或属性值)
十五、深比较,判断是否包含某属性或属性值
1,两个对象进行深比较
(1)isEqual 方法可以执行深比较来确定两者的值是否相等。
该方法支持比较 arrays, array buffers, booleans, date objects, error objects, maps, numbers, Object objects, regexes, sets, strings, symbols, 以及 typed arrays. Object 对象值比较自身的属性。
- 注意:比较时不包括继承的和可枚举的属性。 且不支持函数和 DOM 节点比较。
var object = { 'a': 1 }; var other = { 'a': 1 }; console.log(_.isEqual(object, other)); // => true console.log(object === other); // => false

(2)isEqualWith 方法类似 isEqual。 除了它接受一个 customizer 用来定制比较值。 如果 customizer 返回 undefined 将会比较处理方法代替。
function isGreeting(value) { return /^h(?:i|ello)$/.test(value); } function customizer(objValue, othValue) { if (isGreeting(objValue) && isGreeting(othValue)) { return true; } } var array = ['hello', 'goodbye']; var other = ['hi', 'goodbye']; _.isEqualWith(array, other, customizer); // => true
2,判断是否包含某属性值
(1)isMatch 方法可以执行一个深度比较,来确定 object 是否含有和 source 完全相等的属性值。
(2)isMatchWith 方法类似 isMatch。 除了它接受一个 customizer 定制比较的值。 如果 customizer 返回 undefined 将会比较处理方法代替。
var object = { 'a': 1, 'b': 2 }; _.isMatch(object, { 'b': 2 }); // => true _.isMatch(object, { 'b': 1 }); // => false
(2)isMatchWith 方法类似 isMatch。 除了它接受一个 customizer 定制比较的值。 如果 customizer 返回 undefined 将会比较处理方法代替。
function isGreeting(value) { return /^h(?:i|ello)$/.test(value); } function customizer(objValue, srcValue) { if (isGreeting(objValue) && isGreeting(srcValue)) { return true; } } var object = { 'greeting': 'hello' }; var source = { 'greeting': 'hi' }; _.isMatchWith(object, source, customizer); // => true
3,判断是否是该对象的属性
(1)has 方法可以检查某 path 路径是否是一个 object 对象的直接属性。
(2)hasIn 方法可以检查某 path 路径是否是一个 object 对象的直接属性或继承属性。
var object = { 'a': { 'b': 2 } }; var other = _.create({ 'a': _.create({ 'b': 2 }) }); _.has(object, 'a'); // => true _.has(object, 'a.b'); // => true _.has(object, ['a', 'b']); // => true _.has(other, 'a'); // => false
(2)hasIn 方法可以检查某 path 路径是否是一个 object 对象的直接属性或继承属性。
var object = _.create({ 'a': _.create({ 'b': 2 }) }); _.hasIn(object, 'a'); // => true _.hasIn(object, 'a.b'); // => true _.hasIn(object, ['a', 'b']); // => true _.hasIn(object, 'b'); // => false