Find entry in hash depending on hash's data I wrote this code and I just can't stomach it.
The idea is that there is a schema, and the goal is to find the entry with autoIncrement set to true. If it's not found, the result should be idProperty.
const idProperty = 'id'
const schema = {
  id: { type: 'number' },
  code: { type: 'number', autoIncrement: true },
  email: { type: 'string', trim: 512 }
}

// Find the auto increment field
let autoIncrementSchemaFieldName = null
for (const name in schema) {
  const entry = schema[name]
  if (entry.autoIncrement) {
    autoIncrementSchemaFieldName = name
    break
  }
}
autoIncrementSchemaFieldName = autoIncrementSchemaFieldName || idProperty

console.log('RESULT:', autoIncrementSchemaFieldName)

Is this really the best way to do it?
(To test whether the idProperty fallback works, just rename autoIncrement into autoIncrement2 and run it again)
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)