How to filter nested JSON data from database API response in JavaScript

I’m new to JavaScript and need help filtering data from a database API response. I have a JSON structure with nested objects and I want to filter based on specific field values.

Here’s my data structure:

{
  "items": [
    {
      "uid": "item123abc",
      "properties": {
        "featured": true,
        "cost": 25,
        "item_title": "Widget A",
        "sku": "W001"
      },
      "timestamp": "2021-10-15T14:30:00.000Z"
    },
    {
      "uid": "item456def",
      "properties": {
        "featured": true,
        "cost": 75,
        "item_title": "Widget B",
        "sku": "W002"
      },
      "timestamp": "2021-10-15T14:30:00.000Z"
    },
    {
      "uid": "item789ghi",
      "properties": {
        "cost": 40,
        "item_title": "Widget C",
        "sku": "W003"
      },
      "timestamp": "2021-10-15T14:30:00.000Z"
    }
  ]
}

I tried this code but it doesn’t work:

const getData = async () => {
  const apiUrl = 'https://myapi.example.com/data';
  const response = await fetch(apiUrl);
  const data = await response.json();
  
  // This doesn't work
  const filtered = data.items.filter(item => item.item_title === "Widget A");
  console.log(filtered);
};

How can I properly filter this nested structure by properties like item_title, cost, or any combination of fields?

Your code’s trying to access item.item_title directly, but item_title is actually nested inside the properties object. You need item.properties.item_title instead. Here’s the fix: const filtered = data.items.filter(item => item.properties.item_title === "Widget A");. You can also filter by cost ranges or multiple criteria for better results, like filtering for items with a cost greater than 50 or combining filters for featured items that are cheaper than 30. I’ve made this same mistake before; always double-check your object structure.