B
B
Boris Manzhela2016-04-15 19:10:31
JavaScript
Boris Manzhela, 2016-04-15 19:10:31

Variable in object call in javascript?

There is an object of the form

var book = {
        author__1: {
            name: 'John',
            surname: 'Smith'
        },
        author__2: {
            name: 'John',
            surname: 'Smith'
        }
    };

To get "John" in the console, you need to refer to the value:
console.log(book.author__1.name);

Is it possible and how (if possible) to pass a variable instead of author__1book.author__1.name ? The meaning in the loop goes through all author__{число}of them, pulling data out of them somehow like this:
for (var i=1; i<max; i++) {
        var currentauthor // генерированный каким-то образом
        console.log(book.currentauthor .name);
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Zuev, 2016-04-15
@EKCTPEMICT

var book = {
  author__1: {
    name: 'John',
    surname: 'Smith'
  },
  author__2: {
    name: 'John',
    surname: 'Smith'
  }
};
var max = Object.keys(book).length;

for (var i = 1; i <= max; i++) {
  console.log(book['author__' + i].name);
}

T
TheBububo, 2016-04-15
@TheBububo

In general, the authors ask to be an array

var book = {
  authors: [{
    name: 'John',
    surname: 'Smith'
  },
   {
    name: 'Jack',
    surname: 'Green'
  }]
};
console.log(book.authors[0].name);  // John

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question