2
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ The function returns a copy of $object. Which object? \$\endgroup\$
    – Redu
    Commented Feb 17, 2023 at 19:30
  • \$\begingroup\$ @Redu The object called $object? There's only one. Is that confusing? \$\endgroup\$
    – CJ Dennis
    Commented Feb 21, 2023 at 1:56

1 Answer 1

1
\$\begingroup\$

Objects can have same keys but key values may differ. So I understand you are taking the values from the first one which is $object in your code. Lets put all objects into an array and do something similar in a slightly different way as for a change. I presume they should be similar in performance though.

function objectIntersectKey(...os){
   return os.map(o => Object.keys(o))
            .reduce((p,c) => p.filter(e => c.includes(e)))
            .reduce((r,k) => (r[k] = os[0][k], r), Object.create(null));
}

var os = [ {a: 1, b: 2, c: 3, f: 6, x: 24, z: 26}
         , {b: 2, c: 3, y: 25, z: 26}
         , {a: 1, c: 3, x: 24, z: 26}
         ];

console.log(objectIntersectKey(...os));

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.