1

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?

3 Answers 3

2

Change it to this:

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

or alternatively:

tester.person = person;
tester.friends = friendsArr;
tester.parents = parentsArr;
Sign up to request clarification or add additional context in comments.

Comments

1

You can use dot notation to assign the object keys.

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

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

Comments

0

I think you need to defined the property of the object as an array

Here is your answer

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

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

One thing i need to suggest to all javascript developers.You need to be very carefull while working with arrays.

If you assign a array directly for eg :-tester.friends = friendsArr This will create a reference to friendsArr Object so any change in tester.friends will ultimate cause an change in friendsArr Best way is to create a new array instance and push variable inside.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.