1

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.
6
  • 2
    The real question is why you should have spaces in your keys! Commented Aug 6, 2015 at 13:10
  • 2
    Giving spaces in property names is Bad practice! Commented Aug 6, 2015 at 13:10
  • and not using quotes if you have not allowed character is an error, like spaces for instance Commented Aug 6, 2015 at 13:13
  • @elio.d : this is how i am getting it from API. Commented Aug 6, 2015 at 13:13
  • honestly you should complain ;) Commented Aug 6, 2015 at 13:13

3 Answers 3

3

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']);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.