简体   繁体   中英

How to read space separated key of an object in JavaScript

Help would be appreciated,to read key from an object, the key is separated with space

var Obj = {
    student class: '4th',
    student roll: '24'
}

console.log(obj.student class) ? throws error.
console.log(obj.student roll) ? throws error.

Put it in quotes and use bracket notation.

var Obj = {
  'student class': '4th',
  'student roll': '24'
};

console.log(Obj['student class']);
console.log(Obj['student roll']);

使用方括号表示法:
object['property name']

There are two way to read fields within the object

  1. object.field
  2. object[field]

To access fields having spaces you have to use second option

console.log(Obj['student class']); console.log(Obj['student roll']);

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