如何在JavaScript(含jQuery)中用变量替换JSON属性名?
Hey there! Let's sort out that property access error first, then refine your checkbox-based search to avoid repetitive switch cases—with a little jQuery magic thrown in if you want it.
The Core Issue: Incorrect Property Access Syntax
Your mistake was adding an extra dot before the square brackets. When accessing an object property using a variable, you don't use the dot notation first—just wrap the variable in square brackets directly after the object.
Wrong:
jsonObject.[chktarget] // Syntax error here!
Correct:
jsonObject[chktarget] // No dot before the brackets
Applying This to Your Filter Function
Here's how you can rewrite your existing code to use a dynamic property variable, plus handle both array values (like genre) and regular string values (like artist or year) for broader search flexibility:
// Define your target property (could come from checkbox input later) let chktarget = "genre"; const searchq = "drum 'n' bass"; // Example search term if (searchq !== "") { const filtered = data.filter(jsonObject => { const targetValue = jsonObject[chktarget]; // Handle arrays (like genre) and strings uniformly if (Array.isArray(targetValue)) { return targetValue.some(item => item.includes(searchq)); } else { return targetValue.includes(searchq); } }); console.log("Filtered below"); data = filtered; }
jQuery Optimization for Checkbox-Driven Search
Since you're using jQuery, we can tie this directly to your checkbox inputs to make the search dynamic based on user selection. Let's assume you have checkboxes like this:
<div class="search-options"> <label><input type="checkbox" name="search-field" value="genre" checked> Genre</label> <label><input type="checkbox" name="search-field" value="artist"> Artist</label> <label><input type="checkbox" name="search-field" value="year"> Year</label> </div> <input type="text" id="search-input" placeholder="Search music...">
Then use jQuery to listen for input changes and checkbox selections, with no switch cases needed:
// Store the original data so we can reset when search is empty const originalData = [...yourJsonData]; let data = [...originalData]; // Function to render results (replace with your actual rendering logic) function renderResults(results) { // Example: Clear and repopulate a results list $('#results-list').empty(); results.forEach(item => { $('#results-list').append(`<li>${item.title} by ${item.artist}</li>`); }); } // Handle search input and checkbox changes $('#search-input, input[name="search-field"]').on('input change', function() { const searchq = $('#search-input').val().trim(); // Get the selected search field (default to genre if none checked) const chktarget = $('input[name="search-field"]:checked').val() || 'genre'; if (!searchq) { // Reset to original data when search is empty data = [...originalData]; renderResults(data); return; } // Filter data using dynamic property access const filtered = originalData.filter(jsonObject => { const targetValue = jsonObject[chktarget]; // Make search case-insensitive for better user experience const lowerSearch = searchq.toLowerCase(); if (Array.isArray(targetValue)) { return targetValue.some(item => item.toLowerCase().includes(lowerSearch)); } else { return targetValue.toLowerCase().includes(lowerSearch); } }); data = filtered; renderResults(data); });
This setup automatically adjusts the search field based on which checkbox is selected, and uses the same filtering logic for all fields—no switch cases required!
内容的提问来源于stack exchange,提问作者Vazako

