0

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?

S.Dan
  • 1,826
  • 5
  • 28
  • 55
  • 2
    If you are using ES6, you can write `{ [helperObj]: {} }`. Also read [this](http://stackoverflow.com/questions/9398535/add-dynamic-key-value-pairs-to-javascript-array-or-hash-table). – Aᴍɪʀ Oct 31 '16 at 06:22
  • 2
    [There's no such thing as a "JSON object".](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) – nnnnnn Oct 31 '16 at 06:23
  • 1
    @Aᴍɪʀ it worked and the method in the post too worked. Thanks. – S.Dan Oct 31 '16 at 06:31

1 Answers1

3

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] : {}
};
notgiorgi
  • 1,691
  • 12
  • 27