User Agents

Web browsers and everyday web tech, explained

How to Filter JSON Data in the Browser

· 5 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Filtering JSON data directly in the browser lets you sort through API responses, local files, or embedded datasets without sending anything to a server. You can do it with plain JavaScript's Array.filter(), or use a library like Lodash for more complex logic. This guide covers both approaches, plus how to handle common pitfalls like nested objects and case sensitivity.

What You'll Need

  • A modern browser (Chrome, Firefox, Edge, Safari) with the developer console open (F12 or right-click → Inspect).
  • Your JSON data — either as a local file, a URL endpoint, or a variable you've already defined.
  • Basic understanding of JavaScript syntax (variables, functions, objects).

Step-by-Step

  1. Get your JSON into the browser. If you have a file, use fetch('data.json') inside an async function. If it's an API, replace the URL. For quick testing, you can paste JSON directly into the console as a JavaScript object: const data = [{"name":"Alice","age":30},{"name":"Bob","age":25}].
  2. Understand the structure. Look at your JSON — is it an array of objects? An object with nested arrays? Write down the property names you want to filter on. For example, if you have [{ "product": "shirt", "price": 20 }], you'll filter on product and price.
  3. Use the native filter method. If your JSON is an array, call const filtered = data.filter(item => item.price > 15). This returns a new array with only items where the condition is true. For string matching, use item.product === 'shirt' or item.product.includes('shirt') for partial matches.
  4. Handle nested objects. If your data has nested structures like { "user": { "name": "Alice" } }, access the nested property with dot notation: data.filter(item => item.user.name === 'Alice'). For arrays inside objects, use some() or every() — e.g., data.filter(item => item.tags.some(tag => tag === 'sale')).
  5. Combine multiple conditions. Use logical operators: data.filter(item => item.price > 10 && item.inStock === true). For OR logic, use ||. Wrap complex conditions in parentheses to avoid confusion.
  6. Filter by date or number ranges. For dates, convert strings to timestamps first: new Date(item.date) > new Date('2023-01-01'). For numbers, use comparison operators directly.
  7. Make it case-insensitive. Convert strings to lowercase before comparing: item.name.toLowerCase().includes('alice'). This prevents missing matches when the data has 'Alice' vs 'alice'.
  8. Use a library for complex logic (optional). If you're already using Lodash, its _.filter() accepts a shorthand: _.filter(data, { 'price': 20 }) for exact matches, or _.filter(data, ['price', 20]) for property-value pairs. This is cleaner for multi-field filters.
  9. Display the results. If you're working in a webpage, update the DOM: document.getElementById('output').textContent = JSON.stringify(filtered) or render it as a list. In the console, just type filtered to inspect it.
  10. Test with edge cases. Try filtering with an empty array, null values, or missing properties. Your code should handle these gracefully — for example, use item.price ?? 0 to default missing values.

Common Mistakes

  • Forgetting that filter() returns a new array. The original array is unchanged. If you expect to see the filtered result in the original variable, you'll be confused.
  • Using == instead of ===. Loose equality can cause type coercion issues, e.g., 0 == '' is true. Always use strict equality.
  • Not handling null or undefined. If a property is missing, accessing it throws an error. Use optional chaining: item?.price > 10 or check typeof item.price !== 'undefined'.
  • Assuming all JSON is an array. If your JSON is an object with keys, you need to convert it first: Object.values(data) to get an array of values.
  • Ignoring case sensitivity. 'Shirt' and 'shirt' are different strings. Always normalize with toLowerCase() if you want case-insensitive matches.

Tips

  • Use the browser's console to experiment. You can paste JSON and test filter conditions live without reloading the page.
  • Break down complex filters into steps. First filter by one condition, then chain another filter on the result. This makes debugging easier.
  • Log intermediate results. Add console.log() inside the filter callback to see each item and the condition result.
  • Consider using a search input. For user-facing filtering, attach an event listener to an input field and re-filter on each keystroke.
  • Remember that filter() is read-only. If you need to modify the filtered items, use map() after filtering.

Troubleshooting

  • Nothing is returned. Check if your condition is too strict. Test with a simple condition like item => true to see if the array is populated. Also verify the property names — a typo like item.Price instead of item.price will return false for every item.
  • Error: "Cannot read property 'x' of undefined". This means some items lack the property. Use optional chaining (item?.x) or add a guard: item.x !== undefined && item.x > 10.
  • Filter works in console but not in your script. Check if your script runs before the data is loaded. If using fetch(), make sure you're inside the .then() block or using await in an async function.
  • Results are not updating on the page. You might be overwriting the DOM incorrectly. Use innerHTML or textContent to replace the entire list, not append duplicates.
  • Filtering is slow on large datasets. For arrays with thousands of items, consider using a simple loop with a break condition, or use a Web Worker for heavy processing. But for most cases, native filter is fast enough.

Frequently Asked Questions

Can I filter JSON without writing code?

Yes, you can use browser extensions like JSON Viewer or online tools that let you paste JSON and apply filters via a UI. However, for any custom logic, you'll need JavaScript.

How do I filter by multiple properties at once?

Use && in the condition: data.filter(item => item.category === 'electronics' && item.price < 100). You can chain as many as needed.

What if my JSON is a single object, not an array?

You can't filter a single object directly. Convert it to an array using Object.entries(data) to get key-value pairs, or Object.values(data) to get values, then filter.

Is there a way to filter by regex?

Yes, use item.name.match(/pattern/i) or item.name.includes('substring') for simple cases. For regex, test with regex.test(item.name).

Can I filter and sort in one step?

Not directly, but you can chain: data.filter(...).sort((a,b) => a.price - b.price). Filter first, then sort the result.

How do I filter JSON from an API response?

Use fetch(url).then(res => res.json()).then(data => data.filter(...)). Remember that res.json() returns a promise, so you need to wait for it.