S.Dan
S.Dan

Reputation: 1920

Adding a custom variable as JSON attribute

I'm trying to build a JS object with a custom attribute name. Basically I want to create a Schema based on the root element. ("items" if type is array and "properties" if type is object)

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

The above gives a syntax error:

SyntaxError: missing : after property id

Then I tried to parse a String as a JSON.

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

This gives an error saying:

SyntaxError: JSON.parse: unexpected character at line 1 column 11 of the JSON data

How can I get a JS object as desired?

Upvotes: 0

Views: 716

Answers (1)

notgiorgi
notgiorgi

Reputation: 1771

You could do

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

newSchema[helperObj] = {};

or use if you're using es6:

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

Upvotes: 3

Related Questions