4. Adding properties


#1

Hello,
I don't understand how object creation works :frowning:
I saw there are three posibilities to creat object:

  1. Literal syntax v1
    var myObj = {
    key1: value,
    key2: value
    };

  2. Literak syntax v2
    var myObj = {};
    myObj.key1 = value;
    myObj['key2'] = value;

  3. Object constructor v1
    var myObj = new Object();
    myObj.key1 = value;

Am I correct?
So now i want use Literak sytax v2 like in introduction on this part:


https://www.codecademy.com/en/courses/javascript-beginner-en-3bmfN/0/4?curriculum_id=506324b3a7dffd00020bf661


var friends = {};


friends.bill = {};
  firstName = "Bill";
  lastName = "Gates";
  number = "(206) 555-5555";
  address = ['One Microsoft Way','Redmond','WA','98052'];

friends.steve = {};
  firstName = "Steve";
  lastName = "Jobs";
  number = "(408) 555-5555";
  address = ['1 Infinite Loop','Cupertino','CA','95014'];

I go forward using Literal syntax v1
but I would like understand them all
and second version looks best for me.
So what I'm doing wrong?

Please explain me this.
p.s sorry for my english I do my best.

Greetings


#2

@mehegroth

hello mehegroth,
key and value syntax is
key : value,

Now your code will work

var friends = {};

friends.bill = {
firstName : "Bill",
lastName : "Gates",
number : "(206) 555-5555",
address : ["One Microsoft Way","Redmond","WA","98052"],
};
friends.steve = {
firstName : "Steve",
lastName : "Jobs",
number : "(408) 555-5555",
address : ["1 Infinite Loop","Cupertino","CA","95014"]
};


#3

Hello again,
thanks but it's like first literal syntax and I'd do it in secon
It is possible?
so:
Literak syntax v2
var myObj = {};
myObj.key1 = value;
myObj['key2'] = value;

here is also
key : value

Greetings


#4

OK never mind :slight_smile:
I found solution in different question.

I used user "otavioalban" code
and now it's work

var friends = {};

friends.steve = {};
friends.bill = {};

friends.steve.firstName = "Steve";
friends.steve.lastName = "Smith";
friends.steve.number = "555-0001";

friends.bill.firstName = "Bill";
friends.bill.lastName = "White";
friends.bill.number = "555-0002";

This is what I have in mind.