使用jQuery通过下拉选择框筛选对象数组数据
多条件下拉筛选对象数组解决方案
问题描述
有两个select下拉选择框,希望通过选中的值从对象数组中匹配对应数据。待筛选的对象数组结构示例:
[ {id: 1, name: "Glove black size7", attributes: {d001: {value: 'black'}, d002: {value: '7'}}}, {id: 2, name: "Glove pink size7", attributes: {d001: {value: 'pink'}, d002: {value: '7'}}}, {id: 3, name: "Glove black size8", attributes: {d001: {value: 'black'}, d002: {value: '8'}}} ]
已编写基础jQuery框架,需要完善筛选逻辑。
修正后的完整代码
HTML部分
<div class="variant" data-value='[ {"id": 1, "name": "Glove black size7", "attributes": {"d001": {"value": "black"}, "d002": {"value": "7"}}}, {"id": 2, "name": "Glove pink size7", "attributes": {"d001": {"value": "pink"}, "d002": {"value": "7"}}}, {"id": 3, "name": "Glove black size8", "attributes": {"d001": {"value": "black"}, "d002": {"value": "8"}}} ]'> <select name="d001" id="attribute-d001"> <option value="black">Black</option> <option value="pink">Pink</option> <option value="white">White</option> </select> <select name="d002" id="attribute-d002"> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> </select> </div>
JavaScript部分
$(document).on('change', '.variant select', function(a) { a.preventDefault(); // 收集每个选择框的属性名和对应选中值 var selectedAttrs = $('.variant select').map(function() { return { name: this.name, value: this.value }; }).get(); changeAttribute(selectedAttrs); }) function changeAttribute(selectedAttrs) { // 解析待筛选的数组数据 var variants = JSON.parse($('.variant').attr('data-value')); // 筛选符合所有选中条件的项 var matchedVariants = variants.filter(function(variant) { return selectedAttrs.every(function(attr) { // 确保属性存在且值匹配 return variant.attributes[attr.name] && variant.attributes[attr.name].value === attr.value; }); }); // 处理匹配结果,示例:打印到控制台 console.log('匹配结果:', matchedVariants); // 如需获取首个匹配项 if (matchedVariants.length > 0) { console.log('首个匹配项:', matchedVariants[0]); } }
关键说明
- 修正参数传递:原代码存在
selectedVal笔误,改为传递包含属性名和值的对象数组,避免因选择框顺序变化导致匹配错误。 - 高效筛选逻辑:使用
Array.filter结合Array.every实现多条件精准匹配,确保选中的所有属性都与目标对象的属性值一致。 - 兼容性与健壮性:增加属性存在性判断,避免因对象属性缺失导致的运行报错。
- HTML规范修正:移除重复的
id属性,符合HTML标准。
内容的提问来源于stack exchange,提问作者Chihiro Japan
相关产品推荐
相关产品推荐

