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?