30秒学会 JavaScript 片段 · 2022年4月9日

30秒学会 JavaScript 片段 – Check if object has value

Checks if the target value exists in a JSON object.

  • Use Object.values() to get all the values of the object.
  • Use Array.prototype.includes() to check if the target value is included in the values array.

代码实现

const hasValue = (obj, value) => Object.values(obj).includes(value);

const obj = { a: 100, b: 200 };
hasValue(obj, 100); // true
hasValue(obj, 999); // false

翻译自:https://www.30secondsofcode.org/js/s/object-has-value