You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中用变量替换JSON属性名?

问题解决与优化方案

1. 语法错误修正

你遇到的Unexpected token '['错误,是因为用方括号访问对象属性时多写了一个.。正确写法是直接使用对象[变量名],不需要在对象和方括号之间加.。

修正后的代码:

let chktarget = "genre"; 
var filtered = data.filter(jsonObject => jsonObject[chktarget].includes(searchq)); 

2. 避免Switch Case的通用方案

如果你的复选框对应多个搜索目标(比如title、artist、genre),只需将复选框的选中值赋值给chktarget变量即可,完全不需要写重复的switch case逻辑。

比如绑定复选框选择事件:

// 假设复选框的value就是属性名,比如value="genre"、value="title"
$('input[type="checkbox"]').on('change', function() {
    // 示例取第一个选中的属性,可根据需求调整为多选逻辑
    chktarget = $('input[type="checkbox"]:checked').val() || "genre";
});

如果要兼容字符串类型属性(比如title、artist是字符串,genre是数组),可以扩展判断逻辑让搜索更通用:

var filtered = data.filter(jsonObject => {
    const targetValue = jsonObject[chktarget];
    if (Array.isArray(targetValue)) {
        // 数组类型,检查是否有元素包含搜索词
        return targetValue.some(item => item.toLowerCase().includes(searchq.toLowerCase()));
    } else if (typeof targetValue === 'string') {
        // 字符串类型,直接检查是否包含搜索词
        return targetValue.toLowerCase().includes(searchq.toLowerCase());
    }
    return false;
});

注:加上toLowerCase()可实现不区分大小写的搜索,提升用户体验

3. jQuery替代方案

你可以使用jQuery的$.grep()方法替代原生filter,写法类似:

let chktarget = "genre";
if (searchq !== "") {
    let filtered = $.grep(data, function(jsonObject) {
        const targetValue = jsonObject[chktarget];
        if (Array.isArray(targetValue)) {
            return targetValue.some(item => item.includes(searchq));
        } else if (typeof targetValue === 'string') {
            return targetValue.includes(searchq);
        }
        return false;
    });
    console.log("筛选结果如下");
    data = filtered;
}

内容的提问来源于stack exchange,提问作者Vazako

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.01 13:12:36