0

I'm trying to produce a dynamic variable name for an object so that I can easily find it & modify or delete it after it was created.

It involves a contact list program. (still on local test so far)

example code :

while (choice === 2)
{
     console.log("Add contact");
     var contact = Object.create(Contacts);
     contact+name.initContacts(firstname,age,phone); (user input)
     listContacts.push(contact+name);
     etc.....
}

problem is, it is supposed to be a loop, as long as the user still wants to add more contacts & so on, all contacts will be created with contact object: contact.name; contact.age etc, so i won't be able to find a specific contact with my object name.

I want my object name "contact" to be dynamic & different for each specified contact name inside the list.

example :

contact+name.name = prompt("Enter contact name");

i'd like my object name to look like (contact+name).name = "something"; so if the prompt name is "John" variable should be :

contactJohn.name = "John"; contactJohn.age = "30";

So i can find it easily afterwards.

If i initialize a contact manually :

var listContacts = [];
var contact1 = Object.create(Contacts);
contact1.initContacts("Pittsburg", "Caroline");
var contact2 = Object.create(Contacts);
contact2.initContacts("Nelson", "David");

listContacts.push(contact1);
listContacts.push(contact2);

I've already tried eval() thing, haven't got that much luck so far.

i can easily search those objects by their name : contact1 & contact2.

N0X
  • 1
  • 2
  • 2
    Feels like the you are trying to solve the problem the wrong way. I would have a contacts object and then access the data with something like: contacts.John.age contacts.John.name contacts.... – Marco Magrini Nov 16 '16 at 13:32
  • so you recommend an object.object listing ? with a function that creates a new object.name each time a new user has to be added ? since it's pushed in an array ? instead of having listContacts[0]; listContacts[1];listContacts[2] & so on, it would look like : listContacts[0].name.name ? quite disturbing ? is it supposed to work like this ? – N0X Nov 16 '16 at 13:37
  • 1
    That's not how you do it in JS. If you want to store something under a variable name, that's what object keys are for. –  Nov 16 '16 at 14:08
  • i'll try it that way, see how it goes, but still, in Js there is no possibility to create dynamic variables, was quite surprised about this. – N0X Nov 16 '16 at 14:58

0 Answers0