简体   繁体   中英

JS - extract an Array property from an object

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"]

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 (ie obj['array[]'] and not obj.array[] ) because the property name is not a valid JavaScript identifier, ie 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

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM