How to add key value to javascript object

I am trying to learn JS. It seems simple, but I'm not sure how to do it.

having this javascript object based on this good thread

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

How to add the following value

4: {name: 'John'}

To get the name Eve, I write

 people ["1"]. name
+3
source share
2 answers

Assign the anonymous object as you would any other value.

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

For what it's worth, since your keys are numeric, you can also use indexes with a zero index and make people an array.

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

and

alert( people[2].name ); // outputs Eve
people[3] = { name: 'John' };
+15
source

, :

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

, :

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

:

var somebody = people[1]; /// >>> Sam
0

Source: https://habr.com/ru/post/1709235/


All Articles