How to return an object using the object name as a function parameter?

0

Good evening!

Can someone tell me how I can return the object using an invocation of type:

book (book1);

function book(bookName) {
      var obj = {
        livro1: {
          quantidadePaginas: 300,
          autor: "Jorge",
          editora: "Atlas"
        },
        livro2: {
          quantidadePaginas: 200,
          autor: "Paulo",
          editora: "Cia dos Livros"
        },
        livro3: {
          quantidadePaginas: 150,
          autor: "Pedro",
          editora: "Bartolomeu"
        }
      };
      if (!bookName) {
        return obj;
      };
      return obj.bookName;
    };

When I try to return this way, it appears that book1 is not set.

Where is my thinking wrong?

What do I need to change in the function so that I can return the value of the x (librox) object using the book (book) invocation?

    
asked by anonymous 01.11.2017 / 02:53

3 answers

2

Using obj.bookName you are trying to access the bookName property of obj , which does not exist and therefore returns undefined.

You need to use obj[bookName] instead. So it will try to access the property whose name is equal to the value stored in the bookName variable.

See more about this here: link

    
01.11.2017 / 03:02
2

As luislhl said to access the property whose value comes in the variable passed as argument you will need to use obj[bookName] , but also remember to pass a string in the call of the book("livro1") function. If you call only using book(livro1) the interpreter will expect livro1 to be a previously declared variable.

var livro1 = "livro1"
book(livro1)

If you do not declare the variable or do not pass as a string the error Uncaught ReferenceError: livro1 is not defined will be fired.

    
01.11.2017 / 04:00
1

You can use the eval() method to convert the bookName parameter, but call the function with 'book1' in quotation marks:

    function book(bookName) {
    	
    	var obj = {
    		livro1: {
    			quantidadePaginas: 300,
    			autor: "Jorge",
    			editora: "Atlas"
    		},
    		livro2: {
    			quantidadePaginas: 200,
    			autor: "Paulo",
    			editora: "Cia dos Livros"
    		},
    		livro3: {
    			quantidadePaginas: 150,
    			autor: "Pedro",
    			editora: "Bartolomeu"
    		}
    	};
    	if (!bookName) {
    		return obj;
    	};
    	return eval('obj.'+bookName);
    };
    
    console.log(book('livro1'));
    
01.11.2017 / 04:25