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

Asked

Viewed 784 times

0

good night!

Can anyone tell me how to return the object using a type invocation:

book (booklet 1);

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 my thinking is wrong?

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

3 answers

2


  • Even replacing Return obj.bookName with Return obj[bookName], and invoking book(book1); it still says book1 is not set...

2

Like 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 function call book("livro1"). If you call just using book(livro1) the interpreter will expect livro1 is a previously declared variable.

var livro1 = "livro1"
book(livro1)

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

1

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.