0

I have some object:

var book = {}
book.title = "Big bad book"
book.size = {}
book.size.width = "1 meter"
book.size.height = "2 meter"

I want to get something like this

nameof(book) // book
nameof(book.size) // book.size

or this

book.objectName // book
book.size.objectName // book.size

How can i do this?

6
  • You can't, if you don't want explicitely set book.objectName='book';. Commented Feb 1, 2014 at 15:59
  • 1
    book is the name of a variable referencing your object, not the name of the object. Related: stackoverflow.com/questions/10314338 Commented Feb 1, 2014 at 16:00
  • i have really much objects so i can't do it your way, Teemu :( Commented Feb 1, 2014 at 16:03
  • Have a look at the duplicate question linked in the banner at the top of your question. Commented Feb 1, 2014 at 16:09
  • @OrangeFox Why do you want to do that? Commented Feb 1, 2014 at 16:27

1 Answer 1

0

The name of the object can be retrieved when using a constructor function to create the object:

function Book(){
  this.title = "Big bad book"
  this.size = {}
  this.size.width = "1 meter"
  this.size.height = "2 meter"
}

var book = new Book();
console.log(book.constructor.name);
Sign up to request clarification or add additional context in comments.

2 Comments

Maybe it's fair to tell, that every instance of Book will return the same value, i.e. the name of the constructor function.
console.log(book.constructor.name) Book , not a book `` console.log(book.size.constructor.name) Object , not a book.size

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.