30秒学会 JavaScript 片段 · 2023年9月11日

30秒学会 JavaScript 片段 – Common keys

Finds the common keys between two objects.

  • Use Object.keys() to get the keys of the first object.
  • Use Object.prototype.hasOwnProperty() to check if the second object has a key that’s in the first object.
  • Use Array.prototype.filter() to filter out keys that aren’t in both objects.

代码实现

const commonKeys = (obj1, obj2) =>
  Object.keys(obj1).filter(key => obj2.hasOwnProperty(key));

commonKeys({ a: 1, b: 2 }, { a: 2, c: 1 }); // ['a']

翻译自:https://www.30secondsofcode.org/js/s/common-keys