Soshiribo Soshiribo - 1 month ago 8
Javascript Question

create javascript object with key and value from variables

I've been reading up on javascript and I this site has helped me quite a lot. My goal is to create a javascript object with the "key, value" pair coming from variables. For starters I am trying to create the following javascript object,
If I create like this:

var tester = {
person : "Sarah",
friends : ["Tom", "Nils"],
parents : ["Sandra", "Peter"]
};


That works fine. However trying a different approach:

var tester = {};
var person = "Sarah";
var friendsArr = ["Tom", "Nils"];
var parentsArr = ["Sandra", "Peter"];

tester[person] = person;
tester[friends] = friendsArr;
tester[parents] = parentsArr;


That doesn't work. What am I doing wrong?

Jon Jon
Answer

Change it to this:

tester['person'] = person;
tester['friends'] = friendsArr;
tester['parents'] = parentsArr;

or alternatively:

tester.person = person;
tester.friends = friendsArr;
tester.parents = parentsArr;