I've written a JavaScript function to imitate PHP's array_intersect_key() function for objects. PHP uses arrays as both arrays and objects but JavaScript treats arrays and objects differently. I'm only interested in traditional objects since the equivalent for traditional arrays would be trivial.
The function returns a copy of $object
where each key must exist in all the objects passed in. Otherwise, the key and its value are removed from the returned object. Only the keys of the 2nd, 3rd, etc. objects are important. Their values are ignored. The function is called like
obj = object_intersect_key(obj1);
obj = object_intersect_key(obj1, obj2);
obj = object_intersect_key(obj1, obj2, obj3);
etc.
function object_intersect_key($object, ...$objects) {
$object = Object.assign({}, $object);
for (let comparison_object of $objects) {
$object = Object.fromEntries(Object.entries($object).filter(function (item) {
return this.hasOwnProperty(item[0]);
}, comparison_object));
}
return $object;
}
Is this efficient? Are there better ways of doing this? As far as I know, there's no built-in for this yet.
$object
. Which object? \$\endgroup\$$object
? There's only one. Is that confusing? \$\endgroup\$