How to locate a nested object by matching id property in JavaScript

I’m working with data from an API and need help searching through nested objects. Here’s what my data structure looks like:

record = {
  "attributes": {
    "field1": {"id": "abc123", "value": "content1"},
    "field2": {"id": "def456", "value": "content2"},
    "field3": {"id": "ghi789", "value": "content3"}
  }
}

I have a variable called target_id and I want to search through all the fields in the attributes object. If any field has an id that matches my target_id, I need to get the value from that field. If nothing matches, I should get back null.

This is for a project where I’m syncing data between two systems. Sometimes fields are missing from the response, so I need to check each expected field id to see if it exists in the data. When I find a match, I grab the value and use it. When there’s no match, I just skip that field.

What’s the best way to search through this kind of nested object structure?

Use the find() method - it’s more functional and stops once it finds a match:

const result = Object.values(record.attributes).find(field => field.id === target_id);
return result ? result.value : null;

This is clean and fast since find() returns undefined when there’s no match, so the null check is simple. I use this all the time with REST APIs that have messy field structures. Plus the functional style makes it easy to chain other operations if you need to transform data later.

I’ve worked with similar API structures - Object.entries() is perfect for this. You can destructure the key and value at once:

function findFieldById(record, target_id) {
  for (const [fieldName, fieldData] of Object.entries(record.attributes)) {
    if (fieldData.id === target_id) {
      return fieldData.value;
    }
  }
  return null;
}

Bonus: you get the field name too, which is great for debugging with multiple APIs. Really handy when you need to log which field matched during data syncing.

u can loop through it! just check each attr’s id: for (let field of Object.values(record.attributes)) { if (field.id === target_id) return field.value; } return null; good luck!