-2

I do not understand why I get Uncaught SyntaxError: Unexpected token [ when I do the following:

    var thisarray = ["one","two","three"]
    var thisobj = {
                     thisarray[0] : {thisarray[1] : thisarray[2]}
                  }

There is a similar syntax error that I get from trying this:

$scope.find_settings.find = {$scope.query_main_type:findarray}

here the unexpected token is .. Doesn't javascript resolve the expressions when creating objects or what is happening here?

fbence
  • 2,025
  • 2
  • 19
  • 42

1 Answers1

2

Try either

var thisarray = ["one", "two", "three"]
var thisobj = {
  [thisarray[0]]: {
    [thisarray[1]]: thisarray[2]
  }
}

// Don't use document.write in prod/dev use console.log instead
document.write(JSON.stringify(thisobj));

Or

var thisarray = ["one", "two", "three"]
var thisobj = {};
var thisobj1 = {};

thisobj1[thisarray[1]] = thisarray[2];
thisobj[thisarray[0]] = thisobj1;

document.write(JSON.stringify(thisobj));
Attila Kling
  • 1,717
  • 4
  • 18
  • 32