I am having two objects like below
Object 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"
}
Object 2:
{
"action": "Accept",
"destination_port": "",
"destination_subnet": "0.0.0.0",
"lan_interface": "eth0",
"protocol": "tcp",
"source_port": "",
"source_subnet": "198.168.43.0",
"wan_interface": "wlan0"
}
I would like to compare both objects and check if the values are the same or not. But the object1 might have some properties which are not available in object2.
I have done an implementation like below
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;
}
};
I would like to know whether it can be even simplified with lodash
Use _.isEqual()
to compare the subset of both items (via _.pick()
) that you want to check:
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_port":"","destination_subnet":"0.0.0.0","lan_interface":"eth0","protocol":"tcp","source_port":"","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>
If the 2nd object is always a subset of the 1st, you can use _.isMatch()
instead, but that will only check properties that exist on obj2
:
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_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>