Reputation: 45
I want to create dynamic variables based on the arguments of a function but am having some trouble. I am trying to create a function that
1) takes in a genre name, the parameter,
2) turn it into an object,
3) add relevant info, and
4) push it onto an empty array, called bookshelf.
However, my problem is, when I assign an argument genre = new Object();
, the name of the parameter genre
is name of the object not the argument I give it. So if I put in a genre 'Romance', the object in the bookshelf array is genre not 'Romance'. This is a problem because, I need the array to house different genre names...
var bookshelf = [];
//Input: genre = 'Romance'
function addGenre (genre) {
var genre = new Object ();
genre.someInfo = true;
bookshelf.push(genre);
return bookshelf;
//Ideal output: Romance {someInfo: true}
//Actual output: genre {someInfo: true}
}
//I attempted to use string literals, but I think that's illegal...
function addGenre (genre) {
var `${genre}` = new Object ();
genre.someInfo = true;
bookshelf.push(genre);
return bookshelf;
}
Have a great week :)
Upvotes: 2
Views: 98
Reputation: 4226
I think this is the syntax you want. The square brackets let you use a variable to create a property name for a new object.
const bookshelf = [];
addGenre("romance");
console.log("bookshelf:");
console.log(bookshelf);
function addGenre (genre) {
const newGenre = {
[genre]: {someInfo: true}
};
bookshelf.push(newGenre);
return bookshelf;
}
newGenre
in this example, and array literals are generally preferred over the use of new Object()
and new Array()
, although I don't remember why off the top of my head.)
Upvotes: 2
Reputation: 9782
The genre is a property of the book, the title would be another property.
If you want to create an array of the genres, you can do it as you add books to the array.
"use strict";
let genres = [];
let books = [];
class Book {
constructor(title = "", genre = "") {
if (!genres.includes(genre)) {
genres.push(genre);
}
this.title = title;
this.genre = genre;
}
}
books.push(new Book("Romeo and Juliet", "Romance"),
new Book("Whodunit", "Mystery"),
new Book("Stars", "SciFi"),
new Book("Love and Donuts", "Romance"));
console.log(books);
console.log(genres);
Upvotes: 1