-1

Code:

var obj = {val1: 'Test',val2: 'Test','array[]': [ '1', '1', '1', '1', '1', '1', '1', '1', '1', '1' ] };

console.log(obj.array);

Issue: the above console.log returns undefined. For many, it might be obvious, but I'm a newb and trying to figure out how to log the array[] (it works if the property is simply defined as {'array': ["1", "1", "1", "1", "1", "1", "1", "1", "1", "1"]}).

Expected output: ["1", "1", "1", "1", "1", "1", "1", "1", "1", "1"]

007
  • 2,136
  • 4
  • 26
  • 46

2 Answers2

4

Like this:

console.log(obj['array[]']);

The property you are trying to access is called array[], not array.

You'll have to use square bracket notation to access the property (i.e. obj['array[]'] and not obj.array[]) because the property name is not a valid JavaScript identifier, i.e. a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number.

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

James Hibbard
  • 16,490
  • 14
  • 62
  • 74
1

the object property is named array[], not array. Rename it to array and you will get the results you are expecting.

var obj = {val1: 'Test',val2: 'Test','array': [ '1', '1', '1', '1', '1', '1', '1', '1', '1', '1' ] };

console.log(obj.array);
amyloula
  • 1,556
  • 2
  • 17
  • 26
  • 1
    The above is just an example of the end result of the object. its definition is let obj : {val1:any; val2:any; array:any[];} it names it like that (not user defined). Thanks for your feedback though. – 007 Mar 03 '19 at 19:22