Find entry in hash depending on hash's data
When you want to find a particular matching value in a data structure, using Array.prototype.find is usually the right way to go. It's complicated by the fact that the condition involves the value of the object, but you want the key of the object to be found, so to iterate over the keys and values at once, use Object.entries. It'll give you an array of [key, value] subarrays, and you can return the first item in the resulting subarray to get the key, if anything is found:


const idProperty = 'id';
const schema = {
  id: { type: 'number' },
  code: { type: 'number', autoIncrement: true },
  email: { type: 'string', trim: 512 }
};

const autoIncrementSchemaFieldName = Object.entries(schema)
  .find(([, value]) =&gt; value.autoIncrement)
  ?.[0] // Extract the key from the found entry
  ?? idProperty; // Otherwise, if no entry was found, use idProperty

console.log('RESULT:', autoIncrementSchemaFieldName)



That's what I'd prefer, but there are a few compatibility caveats:

Object.entries was introduced in 2017. It's not new, but it's not old either
I'm using optional chaining and the nullish coalescing operator for conciseness, which is only supported in environments built in 2020 and later

As always, the usual professional solution to compatibility problems is to use Babel to transpile syntax down to ES5 or ES6, and use polyfills to add new built-in objects and methods.
Without ES2020, it'd look like:


const idProperty = 'id';
const schema = {
  id: { type: 'number' },
  code: { type: 'number', autoIncrement: true },
  email: { type: 'string', trim: 512 }
};

const entry = Object.entries(schema)
  .find(([, value]) =&gt; value.autoIncrement);
const autoIncrementSchemaFieldName = entry
  ? entry[0]
  : idProperty;

console.log('RESULT:', autoIncrementSchemaFieldName)