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?

3
  • 2
    If you are using ES6, you can write { [helperObj]: {} }. Also read this. Commented Oct 31, 2016 at 6:22
  • 2
    There's no such thing as a "JSON object". Commented Oct 31, 2016 at 6:23
  • 1
    @Aᴍɪʀ it worked and the method in the post too worked. Thanks. Commented Oct 31, 2016 at 6:31

1 Answer 1

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] : {}
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.