javascript - 添加自定义变量作为 JSON 属性

标签 javascript json

我正在尝试构建一个具有自定义属性名称的 JS 对象。基本上我想创建一个基于根元素的架构。 (如果类型是数组,则为“items”;如果类型为对象,则为“properties”)

    var helperObj = type.toLowerCase() === "array" ? "items" : "properties";
    var newSchema = {
        "title": title,
        "type": type,
        helperObj.toString() : {}
    };

上面给出了一个语法错误:

语法错误:缺少:属性 ID 之后

然后我尝试将字符串解析为 JSON。

    var schemaString="{ \"title\":"+title+", \"type\":"+type.toLowerCase()+","+helperObj+":{}  }";
    var newSchema=JSON.parse(schemaString);

这给出了一个错误:

语法错误:JSON.parse:JSON 数据第 1 行第 11 列出现意外字符

如何获取想要的 JS 对象?

最佳答案

你可以做

var helperObj = type.toLowerCase() === "array" ? "items" : "properties";
var newSchema = {
    "title": title,
    "type": type,
};

newSchema[helperObj] = {};

或者如果您使用的是 es6,请使用:

var helperObj = type.toLowerCase() === "array" ? "items" : "properties";
var newSchema = {
    "title": title,
    "type": type,
    [helperObj] : {}
};

关于javascript - 添加自定义变量作为 JSON 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40337412/

相关文章:

javascript - 结果取回 [object HTMLInputElement]

javascript - 如何获取数组中数字的最大出现次数

javascript - 静态资源转CDN后,google maps在Chrome+Firefox中报错,在Safari中正常 :

javascript - 如何确定 <html> 标签从哪里获得边距

javascript - 使用 Node.JS,如何将 JSON 文件读入(服务器)内存?

javascript - 如何将 JSON 字符串转换为 JavaScript 对象文字

java - 如何用 Java 向 Octoprint 发送 POST 请求?

javascript - 如何选择 3 个独特的数组?

javascript - 如何发回 json 数据类型

Android Volley JsonObjectRequest 不发送参数