I’m seeking assistance with filtering JSON data that contains nested objects. I’m dealing with information retrieved from an external API, and I’m struggling to interact with the nested properties effectively.
The structure of the data I’m using looks like this:
I would like to filter based on properties such as item_title, cost, or sku, but I’m unsure how to correctly access the nested fields. Can anyone guide me on the right approach to do this?
You’re missing the properties path in your filter. Since item_title is nested inside the properties object, use item.properties.item_title instead of item.item_title. I’ve hit this before with nested APIs - try creating a reusable filter function like const filterByProperty = (items, key, value) => items.filter(item => item.properties[key] === value) then call it with filterByProperty(data.items, 'item_title', 'widget A'). Makes the code way cleaner for multiple filters. Just watch out - your third item doesn’t have a featured property, so boolean filters might break if you don’t handle undefined values.
You’re trying to access item_title directly on the item object, but it’s nested inside the properties object.
Here’s the fix:
const getData = async () => {
const apiUrl = 'https://example-api.com/data';
const response = await fetch(apiUrl);
const data = await response.json();
// Filter by item_title
const filtered = data.items.filter(item => item.properties.item_title === "widget A");
// Filter by cost
const expensiveItems = data.items.filter(item => item.properties.cost > 30);
// Filter by featured (note: some items might not have this property)
const featuredItems = data.items.filter(item => item.properties.featured === true);
console.log(filtered);
};
I’ve seen this with similar APIs at work. You might want to check if the nested property exists first, especially if the API doesn’t guarantee all fields:
You’re accessing nested properties wrong. Use item.properties.item_title instead of item.item_title. I hit this exact issue with a product catalog API last year. Optional chaining saved me: data.items.filter(item => item.properties?.featured === true). It stops runtime errors when objects are missing nested fields. For dynamic filtering, try bracket notation: item.properties[propertyName] === targetValue. Super handy when you need different properties based on user input.
Just destructure the properties - way cleaner! const filtered = data.items.filter(({properties}) => properties.item_title === "widget A") works perfectly. You can stack filters too: properties.cost > 25 && properties.featured for complex filtering. Much easier to read.
hey! item_title is nested inside the properties object, not directly on the item. use data.items.filter(item => item.properties.item_title === "widget A") instead. cost and sku work the same way - they’re all under properties so you need the extra dot notation.