How to search for nested object by identifier in JavaScript object structure

I’m working with a JavaScript object that has nested properties, and I need to find a specific item by its identifier. Here’s what my data structure looks like:

record = {
  "attributes": {
    "field1": {"identifier": "abc123", "content": "first_value"},
    "field2": {"identifier": "def456", "content": "second_value"},
    "field3": {"identifier": "ghi789", "content": "third_value"}
  }
}

I have a variable called target_id and I want to check if any of the nested objects has an identifier that matches this value. If I find a match, I need to get the content from that object. If no match exists, I should return null.

This is part of a larger process where I’m syncing data between two systems. Sometimes certain fields are missing from the response, so I need to check each identifier individually to see if the corresponding data exists before trying to use it.

I’ve dealt with similar data structures in API integrations before. The cleanest approach I found is using Object.values() combined with find():

function getContentById(record, target_id) {
  const match = Object.values(record.attributes).find(item => item.identifier === target_id);
  return match ? match.content : null;
}
}

This works great when you’re dealing with dynamic field names - you don’t need to know the exact keys like “field1”, “field2”, etc. I use this pattern all the time for data sync tasks where API responses vary. It’s way more readable than nested loops and won’t throw errors if the structure’s unexpected.

Another option that works great for data sync is building a lookup map first, especially when you’re searching multiple times. Flatten it like this:

const idMap = Object.fromEntries(
  Object.values(record.attributes).map(item => [item.identifier, item.content])
);
const result = idMap[target_id] || null;

This is way more efficient for repeated lookups - build the map once, then access is O(1). I’ve used this when processing huge batches where the same identifiers get hit multiple times. Plus the map makes it easier to debug which identifiers actually exist in your data.

you could also just loop through with for…in if that’s your thing. something like for (let key in record.attributes) { if (record.attributes[key].identifier === target_id) return record.attributes[key].content; } then return null outside the loop. more verbose than find() but some ppl think it’s easier to read.