jsduniya
jsduniya

Reputation: 2474

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.

Upvotes: 1

Views: 78

Answers (3)

pietro909
pietro909

Reputation: 1861

use the square brackets notation:
object['property name']

Upvotes: 0

Hrishi
Hrishi

Reputation: 761

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

Upvotes: 0

Mike
Mike

Reputation: 4091

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

Upvotes: 3

Related Questions