如何解决如何使用lodash检查两个对象的值是否相同
我有两个如下所示的对象
对象1:
{
"action": "Accept","destination_port": "","destination_subnet": "192.168.1.2","id": "59-1601004430291","lan_interface": "eth0","order": 2,"protocol": "any","source_port": "","source_subnet": "192.168.0.0/32","wan_interface": "wlan0"
}
对象2:
{
"action": "Accept","destination_subnet": "0.0.0.0","protocol": "tcp","source_subnet": "198.168.43.0","wan_interface": "wlan0"
}
我想比较两个对象,并检查值是否相同。但是object1可能具有一些object2中不可用的属性。
我已经完成了如下的实现
const isDuplicate = (o1,o2) => {
if (
o1.action === o2.action &&
o1.destination_port === o2.destination_port &&
o1.destination_subnet === o2.destination_subnet &&
o1.lan_interface === o2.lan_interface &&
o1.protocol === o2.protocol &&
o1.source_port === o2.source_port &&
o1.source_subnet === o2.source_subnet &&
o1.wan_interface === o2.wan_interface
) {
return true;
} else {
return false;
}
};
我想知道用lodash是否可以简化它
解决方法
使用_.isEqual()
比较要检查的两项的子集(通过_.pick()
):
const isDuplicate = (...objs) => _.isEqual(...objs.map(o => _.pick(
o,['action','destination_port','destination_subnet','lan_interface','protocol','source_port','source_subnet','wan_interface'],)))
const obj1 = {"action":"Accept","destination_port":"","destination_subnet":"192.168.1.2","id":"59-1601004430291","lan_interface":"eth0","order":2,"protocol":"any","source_port":"","source_subnet":"192.168.0.0/32","wan_interface":"wlan0"}
const obj2 = {"action":"Accept","destination_subnet":"0.0.0.0","protocol":"tcp","source_subnet":"198.168.43.0","wan_interface":"wlan0"}
const result = isDuplicate(obj1,obj2)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>
如果第二个对象始终是第一个对象的子集,则可以改用_.isMatch()
,但这只会检查obj2
上存在的属性:
const obj1 = {"action":"Accept","destination_port":""}
const result = _.isMatch(obj1,obj2)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>
,
修改:对于您的问题,我很抱歉,请重试。
let obj1 = {
"action": "Accept","destination_port": "","destination_subnet": "192.168.1.2","id": "59-1601004430291","lan_interface": "eth0","order": 2,"protocol": "any","source_port": "","source_subnet": "192.168.0.0/32","wan_interface": "wlan0"
};
let obj2 = {
"action": "Accept","destination_subnet": "0.0.0.0","protocol": "tcp","source_subnet": "198.168.43.0","wan_interface": "wlan0"
};
let obj3 = {
"action": "Accept","destination_port": ""
};
let obj4 = {
"action": "Accept","destination_port": ""
};
function comp(obj1,obj2) {
return JSON.stringify(obj1) === JSON.stringify(obj2)
}
console.log(comp(obj1,obj2));
console.log(comp(obj3,obj4));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。