3

I am trying to learn JS. It seems simple but I am not sure how to do this.

having this javascript object based on this good thread

var people = {
  1: { name: 'Joe' },
  2: { name: 'Sam' },
  3: { name: 'Eve' }
};

How do I add the following value

4: { name: 'John' }

To get name Eve I write

 people["1"].name
Community
  • 1
  • 1
kiev
  • 2,040
  • 9
  • 32
  • 54

2 Answers2

15

Assign the anonymous object to it the way you would any other value.

people["4"] = { name: 'John' };

For what it's worth, since your keys are numeric you could also use zero-based indices and make people an array.

var people = [ { name: 'Joe' },
               { name: 'Sam' },
               { name: 'Eve' } ];

and

alert( people[2].name ); // outputs Eve
people[3] = { name: 'John' };
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
1

I think people should be an array :

var people = [
  { name: 'Joe' },
  { name: 'Sam' },
  { name: 'Eve' }
];

as the keys are integers, so you can add a person by :

people.push({name:'John'});

You can acces to the people by doing :

var somebody = people[1]; /// >>> Sam
Fabien Ménager
  • 140,109
  • 3
  • 41
  • 60